---
title: "解决javascript跨域"
author: "angowang"
date: "2015-04-03T10:44:55Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2015-04-03T10:48:49Z"
id: 2198618
url: "https://angowang.iteye.com/blog/2198618"
---

### 1、document.domain+iframe

www.a.com上的a.html

```
document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://script.a.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
    var doc = ifr.contentDocument || ifr.contentWindow.document;
    // 在这里操纵b.html
    alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);
};
```

script.a.com上的b.html

```
document.domain = 'a.com';
```

### 2、动态创建script

```
js.onload = js.onreadystatechange = function() {
    if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        // callback在此处执行
        js.onload = js.onreadystatechange = null;
    }
};
```

### 3、利用iframe和location.hash

先是a.com下的文件cs1.html文件：

```
function startRequest(){
    var ifr = document.createElement('iframe');
    ifr.style.display = 'none';
    ifr.src = 'http://www.cnblogs.com/lab/cscript/cs2.html#paramdo';
    document.body.appendChild(ifr);
}

function checkHash() {
    try {
        var data = location.hash ? location.hash.substring(1) : '';
        if (console.log) {
            console.log('Now the data is '+data);
        }
    } catch(e) {};
}
setInterval(checkHash, 2000);
```

cnblogs.com域名下的cs2.html:

```
//模拟一个简单的参数处理操作
switch(location.hash){
    case '#paramdo':
        callBack();
        break;
    case '#paramset':
        //do something……
        break;
}

function callBack(){
    try {
        parent.location.hash = 'somedata';
    } catch (e) {
        // ie、chrome的安全机制无法修改parent.location.hash，
        // 所以要利用一个中间的cnblogs域下的代理iframe
        var ifrproxy = document.createElement('iframe');
        ifrproxy.style.display = 'none';
        ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata';    // 注意该文件在"a.com"域下
        document.body.appendChild(ifrproxy);
    }
}
```

### 4、使用HTML5 postMessage

a.com/index.html中的代码：

```
<iframe id="ifr" src="b.com/index.html"></iframe>
<script type="text/javascript">
window.onload = function() {
    var ifr = document.getElementById('ifr');
    var targetOrigin = 'http://b.com';  // 若写成'http://b.com/c/proxy.html'效果一样
                                        // 若写成'http://c.com'就不会执行postMessage了
    ifr.contentWindow.postMessage('I was there!', targetOrigin);
};
</script>
```

b.com/index.html中的代码：

```
<script type="text/javascript">
    window.addEventListener('message', function(event){
        // 通过origin属性判断消息来源地址
        if (event.origin == 'http://a.com') {
            alert(event.data);    // 弹出"I was there!"
            alert(event.source);  // 对a.com、index.html中window对象的引用
                                  // 但由于同源策略，这里event.source不可以访问window对象
        }
    }, false);
</script>
```

a.com下的域名cs3.html

```
//因为parent.parent和自身属于同一个域，所以可以改变其location.hash的值
parent.parent.location.hash = self.location.hash.substring(1);
```

### 5、window.name实现的跨域数据传输

1. 在应用页面（a.com/app.html）中创建一个iframe，把其src指向数据页面（b.com/data.html）。  
   数据页面会把数据附加到这个iframe的window.name上，data.html代码如下：
   
   ```
   <script type="text/javascript">
       window.name = 'I was there!';    // 这里是要传输的数据，大小一般为2M，IE和firefox下可以大至32M左右
                                        // 数据格式可以自定义，如json、字符串
   </script>
   ```
2. 在应用页面（a.com/app.html）中监听iframe的onload事件，在此事件中设置这个iframe的src指向本地域的代理文件（代理文件和应用页面在同一域下，所以可以相互通信）。app.html部分代码如下：
   
   ```
   <script type="text/javascript">
       var state = 0, 
       iframe = document.createElement('iframe'),
       loadfn = function() {
           if (state === 1) {
               var data = iframe.contentWindow.name;    // 读取数据
               alert(data);    //弹出'I was there!'
           } else if (state === 0) {
               state = 1;
               iframe.contentWindow.location = "http://a.com/proxy.html";    // 设置的代理文件
           }  
       };
       iframe.src = 'http://b.com/data.html';
       if (iframe.attachEvent) {
           iframe.attachEvent('onload', loadfn);
       } else {
           iframe.onload  = loadfn;
       }
       document.body.appendChild(iframe);
   </script>
   ```
3. 获取数据以后销毁这个iframe，释放内存；这也保证了安全（不被其他域frame js访问）。
   
   ```
   <script type="text/javascript">
       iframe.contentWindow.document.write('');
       iframe.contentWindow.close();
       document.body.removeChild(iframe);
   </script>
   ```

### 6.利用flash

### 7.服务器端开跨域头