有時候,需要修改document.domain。
典型的情形:http://a.xxx.com/A.htm 的主頁面有一個<iframe src="http://b.xxx.com/B.htm"></iframe>,兩個頁面的js如何進行交互?
實現跨域交互的方式有很多,其中這種跨子域的交互,最簡單方式就是通過設置document.domain:只需要在A.htm與B.htm里都加上這一句document.domain = 'xxx.com',兩個頁面就有了互信的基礎,而能無礙的交互。
示例:http://www.wagang.net/jk/document_domain/A.htm
這種實現跨域的方式很簡單,並且主流瀏覽器都支持(IE6+、Firefox、Chrome等)不過,更改document.domain,會有一系列的副作用,為后續的工作留下隱患。
本文收集列舉這些注意事項,以供參考。
1. 如果修改了document.domain,則在某些機器上的IE678里,獲取location.href有權限異常。
例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JK</title> <script> document.domain='wagang.net'; </script> </head> <body > IE678下,有時獲取location.href時有異常:<input type=button value='alert(location.href);' onclick="alert(window.location.href);"> 參見:http://bugs.jquery.com/ticket/8138 jquery ticket#8138 <hr> jQuery中相應的代碼: <pre> // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } </pre><hr> 也可以用:document.URL來獲取:<input type=button value='alert(document.URL);' onclick="alert(document.URL);"> </body> </html>
2. 如果頁面修改了document.domain,則它包含的iframe,必須也設domain,才能進行交互。就算是同域的頁面也必須要設。
這個例子里:http://www.wagang.net/jk/document_domain/A2.htm
由於頁面設了document.domain,導致它包含的本域頁面不能與它交互,因為iframe里的頁面沒有設置document.domain
3. 設置document.doamin,也會影響到其它跟iframe有關的功能。
典型的功能如:富文本編輯器(因為是iframe來做富文本編輯器的)、ajax的前進后退(因為IE67要用到iframe,參見:IE6與location.hash和Ajax歷史記錄)
4. 設置document.doamin,導致ie6下無法向一個iframe提交表單。
這一篇文章里列了問題象與解決方案:IE6與location.hash和Ajax歷史記錄
附:跟跨域相關的幾個參考:
QW.XPC : 利用window.name(IE6、7)和postMessage跨域傳輸數據
屈屈博客: 也談跨域數據交互解決方案
三水清博客: 用document.domain+iframe實現Ajax跨子域