前端跨域处理

2,前端解决跨域问题

  1>document.domain+iframe (只在主域相同的时候才能使用的该方法)

  1)在www.a,com./a.html中:

  

document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://www.script.a.com/b.html';
ifr.display = none;
document.body.appendChild(ifr);
ifr.onload = function(){
    var doc = ifr.contentDocument || ifr.contentWindow.document;
    //在这里操作doc,也就是b.html
    ifr.onload = null;
};

  2)在www.script.a.com/b.html中:

  document.domain = 'a.com';

  2>动态创建script

  由于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, 0);
}
window.baidu = {
  sug: function(data){
    console.log(data);
  }
}
loadScript('http://suggestion.baidu.com/su?wd=w',function(){console.log('loaded')});
//我们请求的内容在哪里?
//我们可以在chorme调试面板的source中看到script引入的内容

  3>location.hash+iframe

  原理是利用location.hash来进行传值。

  假设域名a.com下的文件cs1.html要和cnblogs.com 域名下的cs2.html传递消息。

  1)cs1.html首先创建自动创建一个隐藏的iframe,iframe的src指向cnblogs.com域名下的cs2.html页面。

  2)cs2.html响应请求后再将通过修改cs1.html的hash值来传递数据。

  3)同时在cs1.html上加一个定时器,隔一段时间来判断location.hash值有没有变化,一旦有变化则获取hash值。

  注:由于两个页面不在同一个域下IE、Chrome不允许修改parent.location.hash的值,所有要借助于a.com域名下的一个代理.

  代码如下:

  先是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);
    }
}

  a.com下的域名cs3.html

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

猜你喜欢

转载自www.cnblogs.com/l8l8/p/8962497.html