1. The same origin policy is as follows:

URL instructions Whether to allow communication
www.a.com/a.js www.a.com/b.js Same domain name allow
www.a.com/lab/a.js www.a.com/script/b.js Different folders under the same domain name allow
www.a.com:8000/a.js www.a.com/b.js Same domain name, different port Don’t allow
www.a.com/a.js www.a.com/b.js Same domain name, different protocol Don’t allow
www.a.com/a.js http://70.32.92.74/b.js Domain name and IP address corresponding to the domain name Don’t allow
www.a.com/a.js script.a.com/b.js The same primary domain, but different subdomains Don’t allow
www.a.com/a.js a.com/b.js Same domain name, Different Secondary Domain names (ibid.) Not allowed (cookies are not allowed in this case)
www.cnblogs.com/a.js www.a.com/b.js Different domain name Don’t allow

Note two points in particular: first, if the cross-domain problem is caused by the protocol and port “front” is powerless. Second, in the cross-domain problem, the domain is identified only by the “head of the URL” without trying to determine whether the same IP address corresponds to two domains or whether two domains are on the same IP address. Header of the URL refers to window.location.protocol +window.location.host, which can also be understood as Domains, protocols and ports must match.

The front end solves cross-domain problems

1> document.domain + iframe

(1) In 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; // Perform doc here, i.e. B.html ifr.onload = null; };Copy the code

(2) In www.script.a.com/b.html:

document.domain = ‘a.com’;

2> Create script dynamically

There is nothing to say about this, since script tags are not subject to the same 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 is the content we requested? // We can debug in the Chrome panelsourceSee what script introduces inCopy the code

3> location.hash + iframe

The principle is to use location.hash to pass values.

Suppose the file cs1.html under the domain name a.com wants to communicate with the file cs2.html under the domain name cnblogs.com. 1) cs1.html first creates a hidden iframe automatically, The SRC of the iframe points to the cs2.html page at cnblogs.com. 2) the cs2.html responds to the request and then passes the data by modifying the hash value of the CS1.html. 3) A timer is added to the CS1.html. To determine whether the value of location.hash has changed over a period of time, and if it has, retrieve the hash value. Because the two pages are not in the same domain, Internet Explorer and Chrome do not allow you to change the value of parent-location. hash. Therefore, you need to use a proxy iframe code in the a.com domain as follows:

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);Copy the code

Cs2.html under cnblogs.com domain name:

// Simulate a simple parameter handling operation switch(location.hash){case '#paramdo':
        callBack();
        break;
    case '#paramset': / /doSomething......break;
}

function callBack(){
    try {
        parent.location.hash = 'somedata'; } catch (e) {// The parent.location.hash cannot be fixed by the security mechanism of Ie and Chrome, Iframe var ifrProxy = document.createElement()'iframe');
        ifrproxy.style.display = 'none';
        ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata'; // Note that the file is in"a.com"Domain of the document. The body. The appendChild (ifrproxy); }}Copy the code

The domain cs3.html under a.com

. / / because the parent the parent and its own belong to the same domain, so you can change the location. The hash value of the parent. The parent. The location. The hash = self. The location. The hash. The substring (1);Copy the code

4> window.name + iframe

The beauty of window.name: The name value can still exist after different pages (or even different domain names) are loaded, and very long name values (2MB) can be supported.

1) create 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>Copy the code

3 In b.com/cs1.html:

<script>
    window.name = 'Content to transmit';
</script>Copy the code

5> postMessage (XMLHttpRequest Level 2 API in HTML5)

(1) code in 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'; / / if written'http://b.com/c/proxy.html'The effect is the same'http://c.com'Won't execute postMessage ifr. ContentWindow. PostMessage ('I was there! ', targetOrigin);
};
</script>Copy the code

(2) code in b.com/index.html:

<script type="text/javascript">
    window.addEventListener('message'.function(event){// Use the origin attribute to determine the source address of the messageif (event.origin == 'http://a.com') { alert(event.data); / / the pop-up"I was there!"alert(event.source); // A reference to the window object in a.com, index.html // But because of the same origin policy, event.source cannot access the window object}},false);
</script>Copy the code

6> CORS

The idea behind CORS is to use custom HTTP headers to let the browser communicate with the server to determine whether the request or response should succeed or fail. The implementation of CORS in IE is XDR

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

Implementations in other browsers are in 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);Copy the code

Implement CORS across browsers

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(); }Copy the code

7> JSONP

JSONP consists of two parts: callback functions and data.

The callback function is the function to be called on the current page when the response arrives.

The data is the JSON data passed into the callback function, which is the parameter of the callback function.

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"})*/ // This is how it works: // When we request a script tag // the background will generate json data (handleResponse({handleResponse({handleResponse)})"data": "zhe"})) // Finally the returned JSON data (code) is placed in the current JS file and executed // so the cross-domain communication is completeCopy the code

Jsonp, while simple, has the following disadvantages:

(1) Security problems (there may be security risks in the request code)

(2) It is not easy to determine whether a JSONP request has failed

8> web sockets

Web Sockets is a browser API whose goal is to provide full-duplex, two-way communication over a single persistent connection. (Same origin policy not applicable for Web Sockets)

How Web Sockets Work: After a Web socket is created, an HTTP request is sent to the browser to initiate a connection. After the server responds, the established connection is switched from THE HTTP protocol to the Web SOCKT protocol using the HTTP upgrade.

This function works only on servers that support the Web Socket protocol.

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