---
title: "修改document.domain的注意事项"
author: "jackjobs"
date: "2014-05-07T10:03:00Z"
tags: []
slug: "document-domain"
draft: false
lastmod: "2014-05-22T11:49:38Z"
id: 2069596
url: "https://phantomes.iteye.com/blog/2069596"
---

有时候，需要修改document.domain。

　　典型的情形：http://a.xxx.com/A.htm 的主页面有一个&lt;iframe src="http://b.xxx.com/B.htm"&gt;&lt;/iframe&gt;，两个页面的js如何进行交互？  
　　实现跨域交互的方式有很多，其中这种跨子域的交互，最简单方式就是通过设置document.domain：只需要在A.htm与B.htm里都加上这一句document.domain = 'xxx.com'，两个页面就有了互信的基础，而能无碍的交互。  
　　示例：[http://www.wagang.net/jk/document\_domain/A.htm](http://www.wagang.net/jk/document_domain/A.htm "http://www.wagang.net/jk/document_domain/A.htm")  
　　这种实现跨域的方式很简单，并且主流浏览器都支持（IE6+、Firefox、Chrome等）不过，更改document.domain，会有一系列的副作用，为后续的工作留下隐患。

　　本文收集列举这些注意事项，以供参考。

1\. 如果修改了document.domain，则在某些机器上的IE678里，获取location.href有权限异常。  
例：

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
<!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>
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

2\. 如果页面修改了document.domain，则它包含的iframe，必须也设domain，才能进行交互。就算是同域的页面也必须要设。  
　　这个例子里：[http://www.wagang.net/jk/document\_domain/A2.htm](http://www.wagang.net/jk/document_domain/A2.htm "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历史记录](http://blog.sina.com.cn/s/blog_6e7f61f30100sddm.html)）  
4\. 设置document.doamin，导致ie6下无法向一个iframe提交表单。  
　　这一篇文章里列了问题象与解决方案：[IE6与location.hash和Ajax历史记录](http://www.cnblogs.com/pigtail/archive/2012/06/06/2528136.html "IE6下，设置了domain，导致target指向iframe时，无法打开链接的问题及解决")

附：跟跨域相关的几个参考：  
QW.XPC ：[利用window.name(IE6、7)和postMessage跨域传输数据](https://github.com/wedteam/qwrap/tree/master/resource/js/components/xpc)  
屈屈博客：[也谈跨域数据交互解决方案](http://www.imququ.com/post/84.html)  
三水清博客：[用document.domain+iframe实现Ajax跨子域](http://js8.in/443.html)