8 super detailed Web cross domain solutions

Keywords: Javascript html5 Ajax

1, What is cross domain

When a page or script under the domain name a.qq.com attempts to request resources under the domain name b.qq.com, it is a typical cross domain behavior. The definition of cross domain can be divided into two types: broad cross domain and narrow cross domain.

(1) Generalized cross domain

Generalized cross domain usually includes the following three behaviors:

  1. Resource jump: a link, redirect.

  2. Resource embedding: < link >, < script >, < img >, < frame > and other dom tags, as well as the external chain of files such as background:url(), @ font face () in the style.

  3. Script request: Browser storage data reading, cross domain operation of dom and js objects, ajax request initiated by js, etc.

Among them, resource jump and resource embedding can normally request to cross domain resources. Script requests usually have cross domain problems without any processing.

(2) Homology strategy

The same origin policy (SOP) is an agreement. The browser was introduced by Netscape in 1995. It is the most core and basic security function of the browser. Without the same origin policy, the browser is vulnerable to XSS, CSFR and other attacks. The so-called homology strategy means that "protocol + domain name + port" are the same.

(3) Narrow cross domain

Cross domain in a narrow sense is a kind of request scenario restricted by the browser's homology policy, that is, the cross domain behavior, which usually includes the following three behaviors:

  1. Cookies, localStorage, and indexDB cannot be read.

  2. dom and js objects cannot be retrieved and manipulated.

  3. ajax requests cannot be sent.

2, Common cross domain scenarios

3, Cross domain solutions

(1) ajax cross domain request solution

In the daily development process, most front-end pages will send ajax requests to the back-end for data interaction. So, how to solve the cross domain problem of ajax request. This article summarizes the following four common solutions:

  • jsonp cross domain

JSON with padding (JSON) is a "usage mode" of JSON, which allows web pages to read data across domains. Its essence is to use the open strategy of script tag. The browser passes the callback parameter to the back end. When the back end returns data, the callback parameter will be used as the function name to wrap the data, so that the browser can request data across domains and customize the function to automatically process the returned data.

jsonp cross solution implementation process:

jsonp cross domain code example:

var script = document.createElement('script');script.type = 'text/javascript';// Pass the parameter callback to the back end. When the back end returns, execute the callback function script. SRC = 'defined in the front end http://a.qq.com/index.php?callback=handleCallback '; document.head.appendChild(script);//  Callback execution function function handlecallback (RES) {alert (JSON. Stringify (RES));}

jsonp cross domain advantages:

  • jsonp has strong compatibility and is applicable to all browsers, especially IE10 and below.

jsonp cross domain disadvantages:

  • There is no handling of call errors.

  • Only GET requests are supported, POST requests and requests with large amount of data are not supported, and relevant return headers, status codes and other data cannot be obtained.

  • Malicious injection of callback parameters may cause xss vulnerabilities.

  • Unable to set resource access authorization.

  • Cross domain resource sharing (CORS)

Cross origin resource sharing (CORS) is a W3C standard that allows browsers to send requests to cross domain servers, thus overcoming the limitation that ajax can only be used from the same source. CORS requires both browser and server support. At present, all mainstream browsers (IE10 and above) can support this function by using XMLHttpRequest object. IE8 and IE9 need to be compatible with XDomainRequest object.

The whole communication process of CORS is automatically completed by the browser. Once the browser finds that the ajax request is cross source, it will automatically add the Origin field in the header information to indicate which source the request comes from (protocol + domain name + port). Therefore, the key to realizing CORS communication is the server, which needs to configure access control allow Origin header information. When the CORS request needs to carry cookie s, the server needs to configure the access control allow credentials header, and the front end also needs to set withCredentials.

The browser divides CORS requests into two categories: simple requests and non simple requests. Simple requests need to meet the following two conditions:

  1. The request method is one of the following three methods: HEAD, GET and POST.

  2. The header information of HTTP does not exceed the following fields: Accept, Accept language, content language, last event ID, and content type: only limited to three values: application/x-www-form-urlencoded, multipart / form data, and text/plain.

Cross domain implementation process of CORS simple request:

Cross domain code example of CORS simple request:

// IE8/9 requires XDomainRequest compatibility. var xhr = new XMLHttpRequest()// Whether the front end is set with cookiexhr.withcredentials = true; xhr.open('post', ' http://a.qq.com/index.php ', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('user=saramliu'); xhr.onreadystatechange = function() {    if (xhr.readyState == 4 && xhr.status == 200) {        alert(xhr.responseText);    }};

CORS cross domain benefits:

  • It supports all types of HTTP requests with perfect functions.

  • Handle call errors through onerror event listening;

  • Resource access authorization is performed through access control allow origin.

CORS cross domain disadvantages:

  • At present, mainstream browsers (IE10 and above) support CORS, but IE8 and IE9 need to use XDomainRequest object for compatibility, and IE7 and below do not support CORS.

  • Flash cross domain (for IE7 and below browsers only)

Since IE7 and below browsers are incompatible with cross domain requests by default, Flash can be used for cross domain requests without modifying the back end.

When Flash makes a cross domain request, it will first send a pre check request by default to check the crossdomain.xml file under the root directory of the server domain name to judge whether the requested domain is legal. If the domain name is illegal, Flash directly blocks the request; If the domain name is legal, send a real request, obtain the data and return it to the front-end page.

corssdomain.xml is the main policy file under the target domain, and its file configuration rules are as follows:

(1)cross-domain-policy

The root element of crossdomain.xml contains the following child elements:

  • site-control

  • allow-access-from

  • allow-access-from-identity

  • allow-http-request-headers-from

(2)site-control

Whether to allow other policy files to be loaded. The attribute value allowed cross domain policies allows the following values:

  • none, the policy file (including the main policy file) is not allowed to be loaded.

  • Master only, only the master policy file is allowed to be loaded.

  • By content type, only policy files with content type of text/x-cross-domain-policy under HTTP/HTTPS protocol can be loaded.

  • By FTP filename, only the policy file named crossdomain.xml under the FTP protocol can be loaded.

  • all to allow any policy file to be loaded.

(3)allow-access-from

The request domain used to authorize data access has the following properties:

  • Domain, which specifies the domain to grant permissions. It can be a domain name or IP address.

  • To ports, specify the socket connection port range for which permission is granted, and a comma separated port list. The port range is specified by inserting a dash between two port numbers.

  • secure to specify whether the information is transmitted encrypted.

(4)allow-access-from-identity


Allow request domains with specific certificates to access resources on the target domain across domains.

(5)allow-http-request-headers-from

The request domain used to authorize sending user-defined HTTP headers has the following properties:

  • Domain, which specifies the domain to grant permissions. It can be a domain name or IP address.

  • Headers, indicating the HTTP headers allowed to be sent, separated by commas.

  • secure: indicates whether the information is encrypted.

crossdomain.xml file configuration example:

<cross-domain-policy>    <site-control permitted-cross-domain-policies="all"/>    <allow-access-from domain="*.qq.com"/>    <allow-http-request-headers-from domain="*" headers="*"/></cross-domain-policy>

Flash cross domain implementation process:

Flash cross domain code example:

var FlashHelper = new Object();// Write Flash object flashhelper. Writeflash = function() {var swfname = "Flash4ajax. SWF"; div = document.createelement ("div"); div.style.height = '0'; div.innerhtml = '< object id = "flashdomid" data = "' + swfname + '"' + 'type = "application / x-shockwave Flash"' + 'height = "0" width = "215" >' + '< param name = "movie" value= "'+ swfname +' > '+' < param name =" quality "value =" high "> '+' < param name =" swliveconnect "value =" true "> '+' < \ / Object > '; document.body.appendchild (DIV);} flashhelper. Writeflash(); / / get the Flash object flashhelper. GetFlash = function() {return document. Getelementbyid (" flashdomid ");} / / callback function handlecallback()) {var response = flashhelper. Getflash(). Getvariable ("rettext"); alert (response);} / / send requestfunction request() {var url =“ http://b.qq.com/index.php ";    var method = "GET";    var body = "";    var contentType = "application/x-www-form-urlencoded";    var fs = FlashHelper.getFlash();    fs.XmlHttp(url, "handleCallback ", method, body, contentType);}request();

Flash cross domain benefits:

  • Without changing the back end, it can be compatible with ajax cross domain problems of IE7 and below browsers.

  • The crossdoamin.xml file can be used for authorization access control.

Flash cross domain disadvantages:

  • Limited by the browser's support for Flash plug-ins.

  • Error handling was not invoked.

  • Server agent

Server proxy, as the name suggests, means that when sending a cross domain request, the back-end proxy transfers the request to the server, and then returns the obtained data to the front-end. It is generally applicable to the following scenarios:

When IE7 and below browsers abandon Flash plug-ins, configure the proxy interface to be the same as the front-end page and transfer to the target server interface, then there is no cross domain problem with ajax requests.

The Internet front-end page cannot access the intranet interface. If the proxy interface is configured to allow the front-end page to access and transfer to the intranet interface, the Internet front-end page can access the intranet interface across domains.

Server agent implementation process:

Server agent benefits:

  • It is compatible with cross domain requests of browsers that do not support CORS without Flash.

Server agent disadvantages:

  • The back-end needs a certain amount of transformation.

(2) Front end cross domain communication solution

Front end cross domain communication refers to the communication between two front-end pages in the browser that do not comply with the source policy. So, how to solve this cross domain problem. This article summarizes the following four common solutions:

  • document.domain+iframe

This scheme is only applicable to the cross domain scenario of front-end communication with the same primary domain and different sub domains. As shown in the following figure, there are two pages that do not comply with the contract source policy http://a.qq.com/a.html and http://b.qq.com/b.html Its primary domain is the same as qq.com. a. HTML nested b.html, and then set document.domain as the main domain qq.com through js, then the two pages meet the homology policy, so as to realize cross domain communication.

document.domain+iframe scheme code example:

<!-- A page http://a.qq.com/a.html --><iframe id="iframe" src=" http://b.qq.com/b.html "></iframe><script>    document.domain = "qq.com";     var windowB = document.getElementById("iframe").contentWindow;     Alert ("user variable of B page:" + windowsb. User)</ script>

<!-- B page http://b.qq.com/b.html --><script>    document.domain = "qq.com";    var user = "saramliu";</script>

Advantages of document.domain+iframe scheme:

  • The implementation logic is simple and no additional transfer page is required

Disadvantages of document.domain+iframe scheme:

  • It is only applicable to the cross domain scenario of front-end communication with the same primary domain and different sub domains

  • location.hash+iframe

When two pages that do not conform to the source policy and have different primary domains need cross domain communication, the hash value of the url can be changed without refreshing the page to realize simple front-end cross domain communication.

under normal conditions http://a.qq.com/a.html Embedded in different domains http://b.qq1.com/b.html Restricted by the browser security mechanism, a.html can modify the hash value of b.html, but b.html is not allowed to modify the hash value of a.html, the parent form of different fields. Therefore, this scheme needs a homologous with a.html http://a.qq.com/c.html The implementation process of this scheme is shown in the figure below:

location.hash+iframe scheme code example:

<!-- A page http://a.qq.com/a.html --><iframe id="iframe" src=" http://b.qq1.com/b.html "> < / iframe > < script > / / listen to the hash value from c.html window.onhashchange = function() {alert (" B page transfer data: "+ location. Hash. Substring (1));}</ script>

<!-- B page http://b.qq1.com/b.html --><iframe id="iframe" src=" http://a.qq.com/c.html "> < / iframe > < script > / / pass the hash value var iframe = document.getelementbyid ('iframe ') to c.html; setTimeout(function() {        iframe.src = iframe.src + '#user=saramliu';    }, 1000);</ script>

<!-- C page http://a. QQ. COM / c.html -- > < script > / / listen to the hash value from b.html window.onhashchange = function() {/ / operate the hash value of a.html in the same domain and pass the data window.parent.parent.location.hash = window.location.hash.substring (1);}</ script>

Advantages of location.hash+iframe scheme:

  • It can solve the cross domain problem of front-end communication with different primary domains.

  • If the hash is changed, the page will not be refreshed.

Disadvantages of location.hash+iframe scheme:

  • Restricted by some browser security mechanisms, additional homologous transfer pages are required, and the transfer page needs js logic to modify the hash value.

  • The type and length of communication data are limited, and the data is explicit on the url, so there is a certain security risk.

  • window.name+iframe

The window.name attribute is unique in that the name value still exists after different pages (even different domain names) are loaded, and can support a very long name value (2MB).

As shown in the figure below, http://a.qq.com/a.html Embedded in different domains http://b.qq1.com/b.html . b. When HTML has data to transfer, attach the data to window.name, and then jump to a field with a.html http://a.qq.com/c.html . Because a.html and c.html meet the homology strategy, a.html can obtain the window.name of c.html, so as to realize cross domain communication.

Code example of window.name+iframe:

<!-- A page http://a.qq.com/a.html --><iframe id="iframe" src=" http://b.qq1.com/b.html "></iframe><script>    var state = 0;     var iframe = document.getElementById('iframe');     Iframe.onload = function() {if (state = = = 1) {/ / after the second onload succeeds, read the data alert (iframe. Contentwindow. Name);} else if (state = = = 0) {/ / after the first onload succeeds, state = 1;}}</ script>

<!-- B page http://b. Qq1. COM / b.html -- > < script > window. Name = "here is page B!"; window.location = " http://a.qq.com/c.html ";</ script>

Advantages of window.name+iframe scheme:

  • It can solve the cross domain problem of front-end communication with different primary domains.

  • The communication data type is not limited, and the length can reach 2MB.

Disadvantages of window.name+iframe scheme:

  • An additional homologous transfer page is required, but the transfer page can be blank.

  • postMessage

postMessage is an API in HTML5 XMLHttpRequest Level2 and one of the few window attributes that can operate across domains. It is usually used to solve the following problems:

  1. Data transfer between the page and the new window it opens.

  2. Message passing between multiple windows.

  3. Page and nested iframe messaging.

postMessage is a secure method of cross domain communication. When a.html obtains the window object of b.html, a.html calls the postMessage method to distribute a MessageEvent message. b. HTML can obtain the data transmitted by a.html by listening to the message event, so as to realize cross domain communication. The implementation process of postMessage is shown in the following figure:

The syntax of the postMessage method is as follows:

otherWindow.postMessage(message,targetOrigin,[transfer])

  • otherWindow

The window object of the target window, such as the contentWindow property of iframe, the window object returned by executing window.open, etc.

  • message

Data to be sent to other window s.

  • targetOrigin

Specify which windows can receive message events. The value can be string * (unlimited) or "protocol + host + port number".

  • transfer (optional)

It is a string of Transferable objects delivered simultaneously with the message. The ownership of these objects will be transferred to the message receiver, and the sender will no longer retain the ownership.

Code example of postMessage scheme:

<!-- A page http://A.qq.com/A.html --><iframe id="iframe" src=" http://b.qq1.com/b.html "></iframe><script>    var iframe = document.getElementById('iframe');     Iframe.onload = function() {var data = {meepage: "here is the message sent by page A"}; VAR url =“ http://b.qq1.com/b.html "; / / send the message iframe. Contentwindow. PostMessage (JSON. Stringify (data), URL);} to page B; Window. Addeventlistener ("message", function (E) {alert ("message from page B:" + JSON. Parse (e.data));})</ script>

<!-- B page http://b. Qq1. COM / b.html -- > < script > window. Addeventlistener ("message", function (E) {alert ("message from page A:" + JSON. Parse (e.data)); VAR data = {meepage: "here is the message from page B"}; VAR url =“ http://a.qq.com/a.html ";        window.parent.postMessage(JSON.stringify(data), url);    }, false);</ script>

Advantages of postMessage scheme:

  • It can solve various types of front-end cross domain communication problems;

Disadvantages of the postMessage scheme:

  • The compatibility is relatively poor. IE8 and below browsers do not support this method. IE9 only supports post message to deliver string type data, while the standard post message message data can be of any type.

4, Summary

This paper introduces the browser's cross domain behavior limited by the same origin policy and common cross domain scenarios. This paper summarizes the experience of cross domain problems, and combs the common cross domain solutions and their advantages and disadvantages from the two directions of ajax request and front-end communication, hoping to be a reference for everyone to solve web cross domain problems in daily development. If there is any improper description, I hope you can communicate and correct it at any time.

reference material:
1. Browser homology policy

2. Cross source resource sharing (CORS)

3.Cross-domain AJAX using Flash

4.window.postMessage

Posted by inosent1 on Sun, 10 Oct 2021 07:33:18 -0700