postMessage iframe 跨域通信

参考:

https://www.cnblogs.com/super-yu/p/9480589.html

https://www.jianshu.com/p/17c1cf2f4426

 

  • 同域iframe相互调用:
    1. 子页面调用父页面方法:window.parent.fatherFn();
    2. 父页面调用子页面方法: window.sonFrameName.sonFn();(sonFrameName是iframe的name值)

下面才是重点(一般嵌入iframe的应用应该都是跨域的吧)

  • 跨域iframe相互调用:

window.postMessage

 

示例:

(1)主页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>a域页面</title>
    <style>
        .myIframe {
            width: 500px;
            height: 300px;
            border: ridge;
            border-color: burlywood;
            margin: 15px 0 0 0;
        }
        button {
            color: #fff;
            background-color: #2d8cf0;
            border-color: #2d8cf0;
            border-radius: 4px;
            font-family: inherit;
            text-transform: none;
            display: inline-block;
            padding: 6px 15px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="aaaaa">
        <button onclick="send()">Send Message To Iframe</button>
    </div>
    
    <iframe id="proxy" class="myIframe" src="http://127.0.0.1:8848/test/test2.html" name='frame'></iframe>
    
    <script type="text/javascript">
        function send(){
            var iframe= document.getElementById("proxy");
            if (iframe){
                // * 通配符
                //iframe.contentWindow.postMessage("AAAAA","*");
                // 方法一
                iframe.contentWindow.postMessage("AAAAA", "http://127.0.0.1:8848/test/test2.html");
                // 方法二
                window.frame.postMessage("BBBBB", "http://127.0.0.1:8848/test/test2.html");
            }
        }
    </script>
</body>
</html>

(2)iframe页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>b域页面</title>
    <style>
        .btitle {
            text-align: center;
            margin-top: 10px;
        }
        .bclass {
            width: 100%;
            height: 100px;
            background-color: #3c536b4a;
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div id="bbbbb">
        <div class="btitle">
            <span>I am b page!</span>
        </div>
        <div id="bContent" class="bclass">
        </div>
    </div>
    
    <script type="text/javascript">
        window.onmessage = function(e){
            console.info("received from A is: " + e.data);
        }
    </script>
</body>
</html>

 

原文地址:https://www.cnblogs.com/mengfangui/p/12713224.html