html iframe cross-domain issues

1. child toward his father 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. Chichikoko 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 the parent, the child postMessage, parent monitor the Message;
2. parent to child, parent postMessage, child monitor the Message;
3. Discover the test, son to father postMessage when the source can be written as '*', father to postMessage child when the child's source requires written source, (that is, protocol subpages + host + port number)

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: time after the test, I played respectively by two service node, the parent page at localhost: 8800 on: 8000, sub-pages in localhost

 

Published 84 original articles · won praise 149 · views 50000 +

Guess you like

Origin blog.csdn.net/feifeiyechuan/article/details/105016854