Use postMessage to achieve parent-child communication across domains

Use postMessage to achieve parent-child communication across domains

1. Child communication

parent.html

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

child.html

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

2. Father-child communication

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);
})

Note:
1. Child to parent, child postMessage, parent listening message;
2. Parent to child, parent postMessage, child listening message;
3. Test found that when child to parent postMessage, the source can be written as '*', parent When subpostMessage, the source needs to be written as the source of the sub, (that is, the protocol of the subpage + host number + port)

Test code section:

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: After the test, I started two services using node, the parent page is on localhost: 8000, and the child page is on localhost: 8800

Published 14 original articles · Like 4 · Visitors 8816

Guess you like

Origin blog.csdn.net/weixin_41575159/article/details/95081249