程序目标:点击“打开副本网页”按钮,然后点击“发送信息”向打开的网页发送信息,新开的网页监听并输出接收的信息。两个页面在同个文件夹下网页1<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>主页</title>
</head>
<body>
<button class="open-copy">打开副本网页</button>
<button class="send-msg">发送信息</button>
<script type="text/javascript">
var openCopy = document.getElementsByClassName("open-copy")[0];
var sendMsg = document.getElementsByClassName("send-msg")[0];
openCopy.onclick = function(){
newPage = window.open("practice2.html");
};
sendMsg.onclick = function(){
newPage.postMessage("nihao","practice2.html");
}
</script>
</body>
</html>网页2<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>副本</title>
</head>
<body>
<button class="get-msg">接收打印信息</button>
<script type="text/javascript">
var getMsg = document.getElementsByClassName("get-msg")[0];
window.addEventListener("message",function(e){
newMsg = document.write(e.data);
getMsg.onclick = function(){
console.log(e.data);
}
},false);
</script>
</body>
</html>
添加回答
举报
0/150
提交
取消