postMessage跨域消息传递

window.postMessage() 方法允许来自一个文档的脚本可以传递文本消息到另一个文档里的脚本,而不用管是否跨域。他们可以用这种消息传递技术来实现安全的通信。

这项技术称为“跨文档/跨窗口/跨域消息传递”

postMessage() 方法为异步消息传递。可用于解决以下方面的问题:

1、页面和其打开的新窗口的数据传递
2、页面与嵌套的 iframe 消息传递
3、多窗口之间消息传递

一、语法

otherWindow.postMessage(message, targetOrigin, [transfer]);
参数说明
otherWindow 其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。
message 将要发送到其他 window的数据。
targetOrigin 指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI。
transfer 可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

示例:

window.parent && window.parent.postMessage({ action: 'playerLoaded' }, '*');

this.iframe && this.iframe.contentWindow.postMessage({name: "insertObject", value: fileObj}, "*");

 

二、接收消息

如果指定的源匹配的话,那么当调用 postMessage() 方法的时候,在目标窗口的Window对象上就会触发一个 message 事件。

window.addEventListener("message", (event)=>{
var origin = event.origin;
// 通常,onmessage()事件处理程序应当首先检测其中的origin属性,忽略来自未知源的消息
if (origin !== "http://example.org:8080")
return;
// ...
}, false);

event 的属性有:

data: 从其他 window 传递过来的数据副本。
origin: 调用 postMessage 时,消息发送窗口的 origin。例如:“http://example.com:8080”。
source: 对发送消息的窗口对象的引用。可以使用此来在具有不同 origin 的两个窗口之间建立双向数据通信。

 

实例:

//A页面监听消息,回复消息
const path = `${comm.getHost()}livevideo/?${UrlEncode(searchParams)}`;
const messagefunc = (e) => {
    if (e.data == 'needinfo') {//如果是制定消息
        this.liveIframeRef.current.contentWindow.postMessage({//回复消息
                setwatchInfo: Plaso.userInfo
            },
            path,//指定url
        );
    }
};
window.addEventListener('message', messagefunc);//监听message消息
const closefunc = () => {
    window.removeEventListener('message', messagefunc);
    this.closeLivePage();
};


//B为iframe嵌套页面,发送请求消息,接受数据。
window.parent.postMessage("needinfo",'*');
var userInfo={};
window.addEventListener('message', (event)=>{
    userInfo=event.data;
});//监听message消息

 兼容性:支持ie8

posted @ 2022-07-29 21:09  梁涛999  阅读(420)  评论(0编辑  收藏  举报