这里是同域名下,getmessage.html(发送信息)传递消息给index.html(收到信息,并回传收到信息)
index.html页面
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html charset=utf-8"/>
<title>javascript变量声明的一些测试</title>
<link rel="stylesheet" href="styles.css"/>
</head>
<body>
<div id="firstdiv" style="width:900px;text-align: center;border:10px solid blue">
<form id="form1" action="" method="post">
<input type="button" name="submit1" value="提交"/>
</form>
<p id="msg"></p>
</div>
</body>
<script type="text/javascript" src="test.js"></script>
</html>
这里 是index.html页面中的test.js代码
javascript
const btn=document.getElementsByName('submit1');
btn[0].addEventListener('click',()=>{
let popup=window.open('getmessage.html');
window.addEventListener('message',function(e){
console.log(e);
if(e.origin!='http://xuejs.xyz')return;
//这里收到发来的信息,并显示
document.getElementById('msg').innerHTML=e.data;
e.source.postMessage('收到信息',e.origin);
})
});
javascript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html charset=utf-8"/>
<title>接收postmessage传来的信息</title>
<script type="text/javascript" src="eventutil.js"></script>
</style>
</head>
<body>
<p id="getmsg">waiting for message...</p>
</body>
<script type="text/javascript">
//window.opener表示打开getmessage.html页面的父页面
//这里用postMessage()传递了一条消息给index.html
window.opener.postMessage('super window 接收到一条消息','/');
//下面是接收index.html收到页面后的回传信息
window.addEventListener('message',(e)=>{
console.log(e);
if(e.origin!='http://xuejs.xyz')return;
console.log(e.data);
});
</script>
</html>