💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] * * * * * >跨文档消息传送(cross-document messaging),有时候简称 XDM,指的是来自不同域的页面间传递消息。 * * * * * ### 逻辑描述 ~~~ 1.先取得消息要发送的目的文档的 window 引用 iframe var frame=document.getElementById('frame').contentWindow; js 打开的新标签页 var opener=open('http://localhost:3000'); 2.从当前文档中向目标文档发送消息 targetDocument.postMessage('a string content','http://www.example.com'); //这里的url就明确指定了,接收消息的文档必须来自该url 3.目标文档接到消息 目标文档中要注册事件监听 window.addEventListener('message', function(event) { // 这里可以得到消息的来源,内容等信息 }, false) ~~~ * * * * * ### 实例 ~~~ 在有一个 url 为 http://localhost:3000 的网页里,嵌了一个 url为 http://localhost:3001 的iframe <iframe src="http://localhost:3001/frame/" id="frame"></iframe> 主页面的 js <script type="text/javascript"> var opener; /* 向打开的新标签页发消息 */ document.getElementById('btn').onclick = function() { // 取得目标引用 opener = window.open('/open/'); }; document.getElementById('send').onclick = function() { // 发送消息 opener.postMessage('Hi I am from Main Page !', '*'); } /* 向iframe里发送消息 */ var frame=document.getElementById('frame').contentWindow; frame.postMessage(3333,'http://localhost:3001'); </script> iframe或新标签页里的脚本 <script type="text/javascript"> /* 这里会接收到信息 */ window.addEventListener('message', function(event) { console.log(event); }, false); </script> ~~~ * * * * * ### 参数解释 ~~~ postMessage 方法的参数: 第一个,所要发送的消息,可以为字符串,对象等; 第二个, a. '*' (表示可以被任何文档接收); b. 指定接收方的url,必须有匹配的文档,否则报错; message事件的事件对象event 的主要参数: data 发送过来的数据 origin 调用postMessage方法的文档的 origin source 对发送消息的窗口的对象的引用,可以使用它再次回发内容,双向交互 ~~~ * * * * * >[success] PS:本例使用node的express搭建本地服务做测试,必须是在http协议下才会生效,本地文件不生效