Front-end problem solving cross-domain (rpm)

Original: http://www.cnblogs.com/JChen666/p/3399951.html

1. origin policy: the same IP, with the domain name, with the port, with the agreement

 

2. The front-end to solve cross-domain problems

1> document.domain + iframe (only use this method at the same time the primary domain)

1) In www.a.com/a.html in:

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) In the www.script.a.com/b.html:

document.domain = 'a.com';

2> dynamically created script

This is nothing to say, because the script tag unrestricted-origin policy.

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')});
// Where the content of our request?
// we can see the contents of script introduced in the source chorme debug panel

3> location.hash + iframe

Principle is to use location.hash to traditional values.

Assuming that the file cs1.html under the domain name to a.com and cs2.html under cnblogs.com domain transfer information.
1) cs1.html first create automatically creates a hidden iframe, iframe src to the page under cnblogs.com cs2.html domain
2) cs2.html after the response to the request to transmit data by modifying the hash value cs1.html
3 ) while adding a timer on cs1.html, from time to time to determine the value of location.hash has not changed, once the change is acquired hash value acquired
Note: since the next two pages are not in the same domain IE, Chrome allowed parent.location.hash modified value, so that by means of a proxy to the iframe a.com domain

code is as follows:
file file in the first cs1.html A.com:

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

Under cnblogs.com domain cs2.html:

// simulate a simple processing operation parameter 
Switch (the location.hash) { 
    Case '#paramdo': 
        callBack (); 
        BREAK; 
    Case '#paramset': 
        // do something ...... 
        BREAK; 
} 

function callBack () { 
    the try { 
        = parent.location.hash 'SomeData'; 
    } the catch (E) { 
        // IE, Chrome security mechanism can not be modified parent.location.hash, 
        // so that the agent to be utilized under a iframe intermediate cnblogs domain 
        var ifrproxy = document .createElement ( 'iframes'); 
        ifrproxy.style.display = 'none'; 
        ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata'; // Note that the file "a under .com "domain 
        document.body.appendChild (ifrproxy);
    }
}

Under the a.com domain name cs3.html

// Because parent.parent itself and belonging to the same domain, it may change its value location.hash 
parent.parent.location.hash = self.location.hash.substring (1);

4> window.name + iframe

The beauty of the window.name: name value still exists in the different pages (or even different domain) is loaded, and can support very long name value (2MB).

1) Create a a.com/cs1.html

2) Create a.com/proxy.html, and add the following code

<head>
  <script>
  function proxy(url, func){
    var isFirst = true,
        ifr = document.createElement('iframe'),
        loadFunc = function(){
          if(isFirst){
            ifr.contentWindow.location = 'http://a.com/cs1.html';
            isFirst = false;
          }else{
            func(ifr.contentWindow.name);
            ifr.contentWindow.close();
            document.body.removeChild(ifr);
            ifr.src = '';
            ifr = null;
          }
        };

    ifr.src = url;
    ifr.style.display = 'none';
    if(ifr.attachEvent) ifr.attachEvent('onload', loadFunc);
    else ifr.onload = loadFunc;

    document.body.appendChild(iframe);
  }
</script>
</head>
<body>
  <script>
    proxy('http://www.baidu.com/', function(data){
      console.log(data);
    });
  </script>
</body>

B.com/cs1.html contained in the 3:

< Script > 
    the window.name =  ' to be transferred content ' ;
 </ Script >

5> postMessage (XMLHttpRequest Level API HTML5 in 2)

1) a.com/index.html code:

< Iframes ID = "IFR" the src = "b.com/index.html" > </ iframes > 
< Script type = "text / JavaScript" > 
the window.onload =  function () {
     var IFR = document.getElementById ( ' IFR ' );
     var the targetOrigin =  ' http://b.com ' ;   @ if written' http://b.com/c/proxy.html 'the same effect 
                                        // if written' http://c.com ' It will not be executed postMessage the 
    ifr.contentWindow.postMessage ( 'I was there!', targetOrigin);
};
</script>

2) b.com/index.html code:

< Script type = "text / JavaScript" > 
    window.addEventListener ( ' Message ' , function (Event) {
         // is determined by the source address of the origin attribute 
        IF (event.origin ==  ' http://a.com ' ) { 
            Alert (event.data);     // "! the I WAS there" pop 
            Alert (event.source);   // for a.com, in reference to the window object index.html 
                                  // However, due to the same origin policy, here event.source can not access the window object 
        } 
    }, to false );
 </ Script >

6> CORS

CORS idea behind is to use a custom HTTP headers allow the browser to communicate with the server to determine the request or response should be successful, or should fail.

IE is implemented on CORS xdr

var xdr = new XDomainRequest();
xdr.onload = function(){
    console.log(xdr.responseText);
}
xdr.open('get', 'http://www.baidu.com');
......
xdr.send(null);

Implement other browser in the xhr

var xhr =  new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if(xhr.readyState == 4){
        if(xhr.status >= 200 && xhr.status < 304 || xhr.status == 304){
            console.log(xhr.responseText);
        }
    }
}
xhr.open('get', 'http://www.baidu.com');
......
xhr.send(null);

Cross-browser CORS

function createCORS(method, url){
    var xhr = new XMLHttpRequest();
    if('withCredentials' in xhr){
        xhr.open(method, url, true);
    }else if(typeof XDomainRequest != 'undefined'){
        var xhr = new XDomainRequest();
        xhr.open(method, url);
    }else{
        xhr = null;
    }
    return xhr;
}
var request = createCORS('get', 'http://www.baidu.com');
if(request){
    request.onload = function(){
        ......
    };
    request.send();
}

7> JSONP

JSONP comprising two parts: data and the callback function.

When the callback function is a function in response to the arrival of the current page is called.

Incoming data is json data callback function, which is the parameter of the callback function.

the handleResponse function (Response) { 
    the console.log ( 'IS of The responsed Data:' + response.data); 
} 
var Script = document.createElement ( 'Script'); 
script.src = 'http://www.baidu.com / JSON / = the handleResponse the callback ';? 
document.body.insertBefore (Script, document.body.firstChild); 
/ * handleResonse ({ "Data": "Zhe"}) * / 
// principle is as follows: 
// us when when a request script tag 
// background will be based on the respective parameters (json, the handleResponse) 
// json to generate the corresponding data (the handleResponse ({ "data": "Zhe"})) 
// json data (code returned by the last ) will be placed in the current js file is executed 
// so far completed cross-domain communication

 jsonp although very simple, but has the following disadvantages:

1) the security issues (request code may be a security risk)

2) To determine whether the failure is not easy request jsonp

8> web sockets

It is a browser web sockets API, which goal is a separate persistent connection provides full-duplex, two-way communication. (Same origin policy does not apply to web sockets)

web sockets Principle: After JS created a web socket, there will be a HTTP request is sent to the browser to initiate a connection. After obtaining the server response, connections can be made using HTTP upgrade from HTTP protocol to exchange web sockt agreement.

It works only on the support web socket protocol server.

var socket = new WebSockt('ws://www.baidu.com');//http->ws; https->wss
socket.send('hello WebSockt');
socket.onmessage = function(event){
    var data = event.data;
}

Guess you like

Origin www.cnblogs.com/ganiner/p/11518392.html