8 Scenarios for front-end resolution of cross-domain issues (latest and most complete)

Source: Internet
Author: User

The same-origin policy is as follows:
URL Description whether to allow communication
http://www.a.com/a.js
http://www.a.com/ B.js
under the same domain name allow
http://www.a.com/lab/a.js
Http://www.a.com/script/b.js
different folders under the same domain name Allow
http://www.a.com:8000/a.js
http://www.a.com/b.js
same domain name, different ports do not allow
http://www.a.com/a.js
https://www.a.com/b.js
same domain name, different protocol does not allow
http://www.a. Com/a.js
http://70.32.92.74/b.js
domain name and domain name corresponding IP do not allow
http://www.a.com/a.js
H Ttp://script.a.com/b.js
primary domain, subdomain different not allowed
http://www.a.com/a.js
http://a.com/ B.js
Same domain name, different level two domain name (ibid.) not allowed (cookies are not allowed in this case)
http://www.cnblogs.com/a.js
H Ttp://www.a.com/b.js
different domain names not allowed
Pay special attention to two points:
First, if it is a cross-domain problem caused by protocol and port "front desk" is powerless,
Second: On a cross-domain issue, the domain is only identified by the "header of the URL" and does not attempt to determine whether the same IP address corresponds to two domains or two domains on the same IP.
The "header of the url" refers to Window.location.protocol +window.location.host, which can also be understood as "Domains, protocols and ports must match".
2. Front end solves cross-domain problem 1> document.domain + iframe (this method can only be used when the primary domain is the same)

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;    operate doc here, i.e. b.html    ifr.onload = null;};

2) in www.script.a.com/b.html:

Document.domain = ' a.com ';

2> Dynamic Script Creation

This is nothing to say, because the script tag is not limited by 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 see what the script introduces in the source of the Chorme debug panel

3> Location.hash + iframe

The principle is to use Location.hash to transmit values.

Assume that the file under the domain name a.com cs1.html to and cnblogs.com the cs2.html of the domain name to pass the information.
1) cs1.html first create a hidden iframe,iframe that automatically creates an SRC point to the cs2.html page under the cnblogs.com domain name
2) The cs2.html responds to the request and then passes the data by modifying the hash value of the cs1.html
3) At the same time, add a timer on the cs1.html, interval time to determine whether the value of Location.hash change, once there is a change to get the hash value
Note: Because two pages are not in the same domain IE, chrome does not allow to modify the value of Parent.location.hash, so the use of a proxy iframe under the a.com domain name

The code is as follows:
First the file cs1.html file under 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);

Cs2.html under the cnblogs.com domain name:

Simulates a simple parameter handling operation switch (location.hash) {case    ' #paramdo ':        callBack ();        break;    Case ' #paramset ':        //do something        ... break;} function CallBack () {    try {        parent.location.hash = ' somedata ';    } catch (e) {        //IE, Chrome's security mechanism cannot modify the Parent.location.hash,        //So to take advantage of an intermediary cnblogs domain under the proxy 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 under the "a.com" field        document.body.appendChild (ifrproxy);}    }

The domain name under a.com cs3.html

Because Parent.parent and itself belong to the same domain, they can change the value of their location.hash Parent.parent.location.hash = self.location.hash.substring (1);

4> Window.name + iframe

The beauty of Window.name: Thename value persists after loading different pages (or even different domain names) and can support very long name values (2MB).

1) Create a.com/cs1.html

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

3 included in the b.com/cs1.html:

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

5> PostMessage (API in XMLHttpRequest Level 2 in HTML5)

1) The 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 as ' http://b.com/c/proxy.html ' effect                                        //if written as ' http://c.com ' will not execute postmessage.    Ifr.contentWindow.postMessage (' I was there! ', targetorigin);}; </script>

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

<script type= "Text/javascript" >    window.addeventlistener (' message ', function (event) {        // Use the Origin property to determine the message source address        if (event.origin = = ' http://a.com ') {            alert (event.data);    Eject "I was there!"            alert (event.source);  A reference to the Window object in A.com, index.html                                  //But because of the same Origin policy, here Event.source cannot access the window object        }    , False);</script>
6> CORS

The idea behind Cors is to have the browser communicate with the server using a custom HTTP header to determine whether the request or response should be successful or should 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);
Implementations in other browsers are in XHR
var xhr =  new XMLHttpRequest (); xhr.onreadystatechange = function () {    if (xhr.readystate = = 4) {        if ( Xhr.status >= && xhr.status < 304 | | Xhr.status = = 304) {            console.log (xhr.responsetext);}}    } Xhr.open (' Get ', ' http://www.baidu.com '); Xhr.send (null);
Implementing a 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 contains two parts: callback functions and data.

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

Data is the JSON data that is 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"}) *///principle is as follows:// The corresponding JSON data (Handleresponse ({"Data": "Zhe"}) is generated when we request the script tag//In the background according to the corresponding parameter (json,handleresponse)// Finally, the returned JSON data (code) is placed in the current JS file is executed//so cross-domain communication is completed

Jsonp is simple, but has the following drawbacks:

1) Security issues (security implications may exist in the request code)

2) It is not easy to determine if the JSONP request failed

8> Web sockets

Web sockets is a browser API that aims to provide full-duplex, bidirectional communication on a single, persistent connection. (same-origin policy does not apply to Web sockets)

Web Sockets principle: After JS creates a Web socket, an HTTP request is sent to the browser to initiate the connection. After the server response is obtained, the established connection is switched from the HTTP protocol to the Web Sockt protocol using an HTTP upgrade.

It works only on servers that support the Web socket protocol.

var socket = new Websockt (' ws://www.baidu.com ');//http->ws; Https->wsssocket.send (' Hello Websockt '); socket.onmessage = function (event) {    var data = Event.data;}

8 Scenarios for front-end resolution of cross-domain issues (latest and most complete)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.