版权声明:本文为博主原创文章,未经博主允许不得转载。(转载请指明出处) https://blog.csdn.net/zhangjing0320/article/details/83001596
关于使用PostMessage一般都是和iframe结合一起用,如果你没用到iframe实现了跨域,请留言告知我,感激不尽。
postMessage最重要的两个部分就是
1.发送消息
2.接受消息
需要两个页面A页面和B页面,B页面给A页面发消息,A收到后进行反馈。A是主域。B页面需要通过iframe引入A页面,才能发消息。
A页面: a.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>a页面</title>
</head>
<body>
<script>
// 监听事件
window.addEventListener('message', function(e) {
console.log('listen.....', e);
// 告诉b已经接受到了,然后给他返回。
e.source.postMessage('你要返回的值...', e.origin);
}, false);
</script>
</body>
</html>
B页面: b.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>b页面</title>
</head>
<body>
<iframe id="iframe" src="www.dev.zhangjing.cn/a.html" style="width: 0;height: 0" frameborder="0">
</iframe>
</body>
</html>
<script>
window.onload = function() {
// 给a页面发请求
window.frames[0].postMessage({type:"GET",key:"cms"},'*');
}
window.addEventListener('message', function(e) {
// 接受a反馈的消息
console.log('666', e);
}, false);
</script>
好了,你把这两个文件放到自己的服务器,把b引入iframe的地址(也就是,a页面在服务器的地址)改一下。然后打开服务器上b页面的地址,看开发者命令行下console命令。
正常的输出应该是:
// “isten…”, {}…
// “isten…”, {}…
// “666”, {} …
或者
// “isten…”, {}…
// “666”, {} …
完。