使用postMessage在不同iframe间跨域传递消息

iframe同源策略

如果父窗口访问一个不同域名的子窗口就会报错:
Uncaught DOMException: Blocked a frame with origin "xxx" from accessing a cross-origin frame.
如何解决呢?一个简单的思路就是,既然是因为不同源,那么再建一个同源的窗口不久可以了吗?一个同源的子窗口能读取父窗口无法访问的子窗口的内容,然后通过postMessage传递给父窗口就可以了。

//http://app1.test.local/frame_exec.html
window.onload=function(){
    var h1_content=parent.window.frames['app1'].document.getElementById('frameTitle').innerHTML;
    parent.postMessage({name:'tom',content:h1_content},'http://app2.test.local');
};
<!--http://app1.test.local/iframe.html-->
<h1 id="frameTitle">This is a content in cross domain iframe!</h1>
<!--http://app2.test.local/main_frame.html-->
<iframe name="app1" id="app1" src="http://app1.test.local/iframe.html"></iframe>
<iframe name="app1Exec" id="app1Exec" src="http://app1.test.local/iframe_exec.html"></iframe>
<script>
window.onload=function(){
//Uncaught DOMException: Blocked a frame with origin "http://app2.test.local" from accessing a cross-origin frame.      
    console.info(document.getElementById('app1').contentWindow.document.getElementById('frameTitle'));
};
window.addEventListener('message',function(e){
//{name: "tom", content: "This is a content in cross domain iframe!"}
    console.info(e.data);
},false);
</script>

猜你喜欢

转载自blog.51cto.com/14043491/2367593