HTML5 中的 跨文档消息传送 postMessage()

跨文档消息传送(cross-document messaging),简称XDM,允许来自不同域的页面间传递消息。如 www.test.com 域中的页面与位于内嵌框架中的 c2x.test.com 域中的页面通信。

XDM的核心是 postMessage(dataString, origin),参数:消息字符串,消息接受方所在的域。

 let iframeWindow = document.querySelector("#iframe1").contentWindow;
    let btn = document.querySelector("#btn");

    btn.addEventListener("click",function(e){

        iframeWindow.postMessage("hello XDM","http://www.c2x.test.com");

    },false);

    window.addEventListener("message",function(e){

        console.log(e);
        console.log(e.data);

    },false);

接到XDM消息时, 会触发 window 对象的 message 事件

 message 事件对象,包含三个重要信息:

data:消息字符串

origin:发送消息文档所在的域

source:发送消息的文档的window 对象的代理

    window.addEventListener("message",function(e){

        if(e.origin == "http://www.c2x.test.com"){

            console.log(e);
            console.log(e.data);

            document.querySelector("#testDiv").innerHTML = e.data;
            
            e.source.postMessage("received","http://www.test.com"); // 向来源窗口返回消息,可以不用
        }

    },false);

 因为跨文档消息传送 只能发送字符串消息,所以想要传递结构化数据,需要用JSON.stringify() 转化,然后接到消息后用JSON.parse()转化回来。

猜你喜欢

转载自www.cnblogs.com/zhanglw456/p/10969052.html
今日推荐