postMessage 解决窗口跨域消息传递

来源:互联网 发布:淘宝自定义模板尺寸 编辑:程序博客网 时间:2024/05/22 10:49

现在跨域嵌套的网页通信现在有了新的解决办法了。

postMessage(data,origin)

data是要传递的数据

origin:指明目标窗口源,http://XX.com 这样的。

如果同源就/

如果传递任意*


父页面:

document.querySelector("#child").contentWindow.postMessage('getcolor','http://localhost:8038');

向iframe发送消息。

window.addEventListener('message',function(e){})

绑定接收

子页面:

 window.addEventListener('message',function(e){
                 
                 if(e.source!=window.parent) return;
                 var color=container.style.backgroundColor;
                 window.parent.postMessage(color,'*');
             },false);
接收消息判断访问源和父级是否一样。

用parent访问父级并postMessage发回消息。源是*

 



0 0
原创粉丝点击