2017-10-20 220 views
0

我想了解同源政策。有一個site談論它。但必須有某事。錯與第一例子,因爲我得到一個錯誤Illegal document.domain value同源政策錯誤

這裏是有問題的代碼:

位於http://www.qnimate.com/parent.html父站點:

<iframe src="http://www.blog.qnimate.com/child.html" id="myIFrame"></iframe> 
<script> 
window.document.domain = "www.qnimate.com";//you also need to set the parent's document.domain variable 
window.document.getElementById("myIFrame").contentWindow.document.body.style.backgroundColor = "red";//this access is allowed by default 
</script> 

和iframe位於http://www.blog.qnimate.com/child.html

<script> 
window.document.domain = "www.qnimate.com"; //if we remove this line then the below line will not work and throw a same origin policy exception. 
window.parent.document.body.style.backgroundColor = "blue"; 
</script> 

回答

0

您只能將document.domain設置爲當前域的超級域。您可以從左側移除組件。

當前的域名是www.blog.qnimate.com,所以它可以設置爲blog.qnimate.comqnimate.com

你不能刪除中間的組件,所以你不能有www.qnimate.com


要通過iframe跨越不同來源進行通信,使用postMessage如上所述in this question

+0

好吧,所以上面的例子是不正確的? – Mulligun81

+0

@ Mulligun81 - 是的。您觀察到的示例代碼拋出錯誤是不正確的。 – Quentin