使用postMessage来实现父子通信跨域

4年以前  |  阅读数:226 次  |  编程语言:JavaScript 

1.子向父通信

parent.html

window.addEventListener('message',function(e){
        console.log(e.data);
        if(e.data.msg==='xxx'){
                //一些自己的业务逻辑
            }
});

child.html

window.parent.postMessage({
         msg:"xxx"
},'*');

2.父向子通信

parent.html

var myframe = document.getElementById('myframe');//获取iframe
myframe.contentWindow.postMessage({data:'parent'},childDomain);//childDomain是子页面的源(协议+主机+端口号)

child.html

window.addEventListener('message', function(e){
      console.log(e.data.data);
})

注意:

  1. 子向父,子postMessage,父监听message;
  2. 父向子,父postMessage,子监听message;
  3. 测试发现,子向父postMessage的时候,源可以写为‘*’,父向子postMessage的时候,源需要写成子的源,(也就是子页面的协议+主机号+端口)

测试代码部分:

parent.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>iframe父级页面</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        iframe {
            width: 200px;
            height: 200px;
        }
    </style>

</head>
<body>
    <h2>我是父级页面</h2>
    <button id='btn'>父页面的按钮</button>
     <div id="default">div内容</div>
    <iframe src="http://localhost:8800/child.html" frameborder="0" name='myframe' id='myframe'></iframe>
    <script language="javascript" type="text/javascript">
         window.addEventListener('message',function(e){
            console.log(e.data);
            if(e.data.msg==='hideselfService'){
                document.getElementById('default').style.display = 'none';
            }
        });
         document.getElementById('btn').onclick= function(){
             var myframe = document.getElementById('myframe');
            myframe.contentWindow.postMessage({data:'parent'},'http://localhost:8800');
         }
    </script>
</body>
</html>

child.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>iframe子页面</title>
</head>
<body>
    <h2>我是内嵌的子页面</h2>
    <button id='btn'>子页面的按钮</button>
    <script>
         document.getElementById('btn').onclick= function(){
            window.parent.postMessage({
                msg:"hideselfService"
            },'*');
        }
        window.addEventListener('message', function(e){
            console.log(e.data.data);
        })
    </script>
</body>
</html>

tips:测试后的时候,我是分别用node起了两个服务,父页面在localhost:8000上,子页面在localhost:8800上

 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
将二进制数据转为16进制以便显示
获取IMSI
获取IMEI
Java生成UUID
PHP自定义函数获取搜索引擎来源关键字的方法
让你成为最历害的git提交人
在Zeus Web Server中安装PHP语言支持
指定应用ID以获取对应的应用名称
再谈PHP中单双引号的区别详解
Python 2与Python 3版本和编码的对比
php+ajax+json 详解及实例代码
Yii2汉字转拼音类的实例代码
php封装的page分页类完整实例
php数组合并array_merge()函数使用注意事项
PHP实现简单爬虫的方法
PHP设计模式之工厂模式与单例模式
php实现数组中索引关联数据转换成json对象的方法
wget使用技巧