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


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上

 

 

文章轉自:https://www.jianshu.com/p/e558f4115c82


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM