如果父窗口訪問一個不同域名的子窗口就會報錯:
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 h2_content=parent.window.frames['app1'].document.getElementById('frameTitle').innerHTML;
parent.postMessage({name:'tom',content:h2_content},'http://app2.test.local');
};
<!--http://app1.test.local/iframe.html-->
<h2 id="frameTitle">This is a content in cross domain iframe!</h2>
<!--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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。