修改document.domain的注意事项

有时候,需要修改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跨子域

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值