有时候,需要修改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);' οnclick="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.locationajaxLocation = document.createElement( "a" );ajaxLocation.href = "";ajaxLocation = ajaxLocation.href; }</pre><hr>也可以用:document.URL来获取:<input type=button value='alert(document.URL);' οnclick="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跨子域
转载于:https://www.cnblogs.com/huojing/p/3904440.html