使用postMessage來實現父子通信跨域

3年以前  |  閱讀數:57 次  |    

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上

相關文章:

18禁止午夜福利体验区,人与动人物xxxx毛片人与狍,色男人窝网站聚色窝,女生把筷子放屁眼里,国产精品久久久,国产日产欧洲无码视频