可应用于如下场景:
页面和其打开的新窗口的数据传递
页面与嵌套的 iframe 消息传递
多窗口之间消息传递
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sender</title>
</head>
<body>
<script>
// 发送
function send(){
window.postMessage('hello world','http://kangbao.wszx.cc');
console.log('send');
}
// 接收
window.addEventListener("message", (e)=>{
// 首先检测其中的origin属性,忽略来自未知源的消息
console.log(e);
});
</script>
<button onclick="send();">发送</button>
</body>
</html>
注意:调用postMessage方法的可以是打开的新窗口,iframe,这样的话去对应的页面写接收逻辑,就可以收到消息,我这里为了方便测试,用window对象发送,相当于自己给自己发送,所以也用window对象接收。