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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2020-07-29 OBJ格式模型详细介绍