使用 iframe + postMessage 实现跨域通信

本文通过示例介绍了如何使用HTML的postMessage方法在父页面和子页面之间进行通信。在parent.html中,父页面向子页面child.html发送消息,并监听接收子页面的回复。而在child.html中,子页面接收到父页面的消息后,也会向父页面发送一条消息。此过程展示了iframe跨域通信的基本用法和注意事项,确保在页面完全加载后执行postMessage操作。
摘要由CSDN通过智能技术生成

创建两个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对象,这些对象的所有权将被转移给消息的接收方,而发送方将不再保留所有权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值