跨域

什么是跨域

协议,域名,端口任何一项不同都会引起跨域问题
注意: 下面讨论的解决方案都是针对于域名引起的跨域的,协议和端口的跨域前端无能为力

跨域解决方案

1.document.domain + iframe

只有主域相同才能使用

//parent.domain.com/a.html
document.doman = 'domain.com'
var ifr = document.createElement('iframe')
ifr.src = 'child.domain.com/b.html'
ifr.display = none;
document.body.appendChild(ifr);
ifr.onload = function () {
    var doc = ifr.contentDocument || ifr.contentWindow.document
    //doc 
     ifr.onload = null;
}

//child.domain.com/b.html
document.domain = 'domain.com'

2.动态创建script

function loadScript(url, func) {
  var head = document.head || document.getElementByTagName('head')[0];
  var script = document.createElement('script');
  script.src = url;

  script.onload = script.onreadystatechange = function(){
    if(!this.readyState || this.readyState=='loaded' || this.readyState=='complete'){
      func();
      script.onload = script.onreadystatechange = null;
    }
  };

  head.insertBefore(script, null);
}
window.baidu = {
  sug: function(data){
    console.log(data);
  }
}
loadScript('http://suggestion.baidu.com/su?wd=w',function(){console.log('loaded')});    

3.loaction.hash+ iframe

    //a.com/a.html
function startRequest(){
    var ifr = document.createElement('iframe');
    ifr.style.display = 'none';
    ifr.src = 'http://b.com/b.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);


//b.com/b.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/c.html#somedata';    // 注意该文件在"a.com"域下
        document.body.appendChild(ifrproxy);
    }
}    


//http://a.com/c.html
parent.parent.location.hash = self.location.hash.substring(1);

4.window.name + iframe

window.name :name 值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)

    //a.com/a/html
            function proxy(url,func) {
    var isFirst = true;
    var ifr = document.createElement('iframe');
    loadFunc = function() {
        console.log(1,isFirst)
        if(isFirst) {
            ifr.src = 'a.com/cs1.html';
            isFirst = false;
        } else {
            console.log('name',ifr.contentWindow.name)
            func(ifr.contentWindow.name);
            document.body.removeChild(ifr);
            ifr.src = null;
            ifr = '';
        }

    }
     ifr.src = url;
    ifr.style.display = 'none';
    if(ifr.attachEvent){ ifr.attachEvent('onload', loadFunc);
}else {ifr.onload = loadFunc;}
     document.body.appendChild(ifr);
}

 proxy('http://www.baidu.com/', function(data){
      console.log('data',data);
    });

5. 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
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);

6.CORS

7.JSONP

    function handleResponse(response){
    console.log('The responsed data is: '+response.data);
}
var script = document.createElement('script');
script.src = 'http://www.baidu.com/json/?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);
/*handleResonse({"data": "zhe"})*/
//原理如下:
//当我们通过script标签请求时
//后台就会根据相应的参数(json,handleResponse)
//来生成相应的json数据(handleResponse({"data": "zhe"}))
//最后这个返回的json数据(代码)就会被放在当前js文件中被执行
//至此跨域通信完成

8.web socket