使用 iframe + postMessage 实现跨域通信

创建两个html页面

1.创建父页面parent.html

代码如下:

<body>
    <h1>parent</h1>
    <iframe id="child" name="child" src="http://127.0.0.1:5500/child.html" frameborder="0"></iframe>
    <script>
        window.onload = function () {
            var child = window.child
            // 给child发送消息
            child.postMessage("123456789", "*")
            /* dom写法
             var child=document.getElementById("child")
             child.contentWindow.postMessage("123456789", "*")
            */
            // 接受子消息
            window.addEventListener('message', function (event) {
                console.log(event,"我接收到了子传递的消息");
            }, false);
        }
    </script>
</body>

2.创建子页面child.html
代码如下:

<body>
    <h1>child</h1>
    <script>
        window.addEventListener('message', function (event) {
            // 打印父传过来的消息
            console.log(event, "收到父页面传过来的参数");
            // 给父传消息
            top.postMessage("传给父的消息", '*')
        }, false);
    </script>
</body>

注意事项:

1.一定是页面加载完成后在发送消息,否则会因为 iframe 未加载完成报错。

Failed to execute 'postMessage' on 'DOMWindow'

2.语法:otherWindow.postMessage(message, targetOrigin, [transfer]);

	otherWindow:其他窗口的引用,如 iframe的contentWindow、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
	message:将要发送到其他window的数据。
	targetOrigin:指定那些窗口能接收到消息事件,其值可以是字符串 “*” 表示无限制,或者是一个URI。
	transfer:是一串和message同时传递的Transferable对象,这些对象的所有权将被转移给消息的接收方,而发送方将不再保留所有权。

版权声明:本文为xy13983447577原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。