欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

搞定iframe父子间跨域通信,一篇文章全告诉你!——之二

最编程 2024-01-22 17:20:28
...

可以通过postMessage来实现通信。

otherWindow.postMessage(message, targetOrigin, [transfer]);

其中的参数:

otherWindow
目标窗口。比如 iframe 的 contentWindow 属性

message
将要发送到其他 窗口 的数据。

targetOrigin
目标窗口的域。其值可以是字符串"*"(表示无限制)或者一个 URI。不提供确切的 targetOrigin 将导致数据泄露到任何对数据感兴趣的恶意站点。

现在有两个不同源的 iframe 嵌套页面,父页面http://127.0.0.1:8001/parent.html,子页面http://127.0.0.1:8002/child.html(本地分别对两个html起了两个服务),其中父页面嵌套部分代码如下:

// http://127.0.0.1:8001/parent.html
<iframe
  id='testIframe'
  name='test'
  src='http://127.0.0.1:8002/child.html'
  frameborder='0'
  scrolling='no'>
</iframe>

1. 父页面发送信息,子页面接收信息

// http://127.0.0.1:8001/parent.html
// 父页面发送信息
document.getElementById('testIframe').onload = function () {
    test.window.postMessage('hello, child!', 'http://127.0.0.1:8002');
}

// http://127.0.0.1:8002/child.html
// 子页面接收信息
window.addEventListener('message', e => {
    // 通过origin对消息进行过滤,避免遭到XSS攻击
    if (e.origin === 'http://127.0.0.1:8001') {
        console.log(e.origin) // 父页面所在的域
        console.log(e.data)  // 父页面发送的消息, hello, child!
    }
}, false);

2. 子页面发送信息,父页面接收信息

// http://127.0.0.1:8002/child.html
window.top.postMessage('hello, parent!', 'http://127.0.0.1:8001');

// http://127.0.0.1:8001/parent.html
window.addEventListener('message', e => {
    // 通过origin对消息进行过滤,避免遭到XSS攻击
    if (e.origin === 'http://127.0.0.1:8002') {
        console.log(e.origin) // 子页面所在的域
        console.log(e.data)  // 子页面发送的消息, hello, parent!
    }
}, false);

通过postMessagewindow.addEventListener('message', e => { ... })配合使用,我们就能够完成跨域 iframe 父子页面的通信。

当然对于同源的 iframe 父子页面也可以采用postMessage的方式来发送接收信息。

参考资料:

postMessage APIdeveloper.mozilla.org/zh-CN/docs/…
iframe 跨域通信(postMessage)juejin.cn/post/684490…

本文由mdnice多平台发布