A summary of JavaScript cross-domain issues

Source: Internet
Author: User

What is cross-domain?

Concept: As long as the protocol, domain names, ports are any different, are treated as a different domain.

URL description whether to allow traffic to http:Www.a.com/a.jshttp://www.a.com/b.js the same domain allows Http://www.a.com/lab/a.jshttp:< Span class= "Hljs-comment" >//www.a.com/script/b.js different folders under the same domain allow Http://www.a.com:8000/ A.jshttp://www.a.com/b.js the same domain name, different ports do not allow Http://www.a.com/ A.jshttps://www.a.com/b.js the same domain name, different protocols do not allow Http://www.a.com/ A.jshttp://70.32.92.74/b.js domain name and domain name corresponding IP does not allow Http://www.a.com/ A.jshttp://script.a.com/b.js primary domain, different subdomains do not allow Http://www.a.com /a.jshttp://a.com/b.js the same domain name, different level two domain names (ibid.) do not allow (cookies are not allowed in this case) http: //www.cnblogs.com/a.jshttp://www.a.com/b.js different domain names not allowed 

The differences between ports and protocols can only be resolved through the background.

Cross-domain resource sharing (CORS)

CORS(Cross-Origin Resource SharingCross-domain resource sharing, which defines how the browser and server should communicate when accessing cross-domain resources. CORSThe basic idea behind this is to use a custom HTTP header to communicate with the server to determine whether the request or response should succeed or fail.

<type="Text/javascript" >    new XMLHttpRequest (); Xhr.open ("/trigkit4",True ); Xhr.send (); </script>       

The above trigkit4 is the relative path, if we want to use it CORS , the relevant Ajax code might look like this:

<type="Text/javascript" >    new XMLHttpRequest () Xhr.open ("http:// segmentfault.com/u/trigkit4/",true); Xhr.send (); </script>       

The difference between the code and the previous one is that the relative path is replaced by the absolute path of the other domain, which is the interface address you want to access across domains.

Server-side CORS support, mainly through the setup Access-Control-Allow-Origin to do. If the browser detects the appropriate settings, it can allow Ajax for cross-domain access.

To resolve cross-domain issues, we can use the following methods:

Cross-domain through JSONP

What's the problem now? What's that jsonp ? Wikipedia is defined as JSONP(JSON with Padding) JSON a "usage model" of the data format that allows the Web page to have data from other domains.

JSONPAlso called a fill json, is a new way to apply JSON, but is a JSON that is contained in a function call, for example:

Callback ({"name","TRIGKIT4"}); 

JSONP consists of two parts: the callback function and the data. The callback function is the function that should be called in the page when the response arrives, and the data is the JSON data that is passed into the callback function.

In JS, it XMLHttpRequest is not possible for us to request data directly from different domains. However, it is possible to introduce JS script files on different domains on the page, and JSONP is using this feature to achieve this. For example:

<type="Text/javascript" >    dosomething (//processing obtained JSON data}</script> <src="http://example.com/data.php?callback=dosomething" ></script> 

JS file loading will execute the function we specified in the URL parameter, and we will pass in the JSON data we need as parameters. So JSONP is the server side of the page to do the corresponding match.

<?php$callback = $_get[' callback '];  Array (' a ',' B ',' C ');  The data to return echo $callback.' ('. Json_encode ($data). ') '; //Output ?>          

Finally, the output is:dosomething([‘a‘,‘b‘,‘c‘]);

If your page uses jquery, it is easy to jsonp with the method it encapsulates.

<type="Text/javascript" >    $.getjson (//processing obtained JSON data});  </script>     

jquerywill automatically generate a global function to replace callback=? the question mark in the, and then get to the data and then automatically destroyed, in fact, the role of a temporary agent function. The $.getJSON method will automatically determine whether it is cross-domain, not cross-domain, call ajax the normal method, cross-domain, it will be asynchronously loaded JS file in the form of the call jsonp callback function.

Advantages and disadvantages of JSONP

The advantage of JSONP is that it is not subject to the XMLHttpRequest same-origin policy as AJAX requests for object implementations, that it is more compatible and can be run in older browsers without the need for XMLHttpRequest or ActiveX support , and after the request is complete, the result can be returned by calling callback.

The disadvantage of JSONP is that it only supports get requests and does not support other types of HTTP requests such as Post, which only supports cross-domain HTTP requests, and does not solve the problem of how calls are made between two pages in different domains JavaScript .

Cors and Jsonp Comparison

Compared with JSONP, Cors is undoubtedly more advanced, convenient and reliable.

1. JSONP can only implement get requests, and Cors supports all types of HTTP requests.

2, using cors, developers can use ordinary XMLHttpRequest to initiate requests and obtain data, than JSONP have better error handling.

3. JSONP is primarily supported by older browsers, which often do not support cors, and most modern browsers already support Cors.

To cross subdomains by modifying document.domain

Browsers have a single origin policy, one of the limitations of which is that the first method we say cannot be used in Ajax to request documents from different sources. The second limitation is that there is no interaction between the frames of different domains in the browser.

A Window object can be obtained between different frames, but the corresponding properties and methods cannot be obtained. For example, there is a page, its address is http://www.example.com/a.html , in this page there is a iframe , its src is http://example.com/b.html , it is clear that this page and its iframe framework is different domain, so we are not able to write in the page JS code to get iframe things in:

<ScriptType="Text/javascript" >    functionTest){var iframe =document.getElementById (var win = document.contentwindow; You can get to the Window object in the IFRAME, but the properties and methods of the Window object are almost unusable var doc = Win.document;//here does not get the document object in the IFRAME var name = Win.name; The Name property of the Window object is also not available here}</script> <iframe id =  "iframe" src= "http://example.com/b.html" onload =  "test ()" ></IFRAME>             

This time, document.domain it can come in handy, we just have to http://www.example.com/a.html the http://example.com/b.html two pages of the document.domain are set to the same domain name can be. Note, however, that the document.domain setting is limited, and we can only set Document.domain to the parent domain of itself or higher, and the primary domain must be the same.

1. On the page, http://www.example.com/a.html set document.domain :

<IframeID ="IFRAME"Src= "http://example.com/b.html" onload =  "Test ()" ></iframe><script type= "Text/javascript" > document.domain =  ' example.com '; //set to primary domain function  Test (document.getelementbyid ( //contentwindow can get the Window object of child window} </SCRIPT>         

2. http://example.com/b.html also set in the page document.domain :

<type="Text/javascript" >    ' example.com ';  In the iframe loading this page also set Document.domain, so that it is the same as the main page document.domain </script>    

document.domainthe modified method only applies to the interaction between frames of different subdomains.

Using Window.name for cross-domain

windowAn object has a name property that has a feature: that is, in the lifetime of a window, all the pages loaded into the window are shared window.name , each page pair window.name has read and write permissions, and window.name is persistent in all pages loaded with a window.

Cross-domain using HTML5 's Window.postmessage method

window.postMessage(message,targetOrigin)Method is a html5 newly introduced feature that can be used to window send messages to other objects, regardless of whether the window object is of the same origin or different source, and the current IE8+、FireFox、Chrome、Opera browser has supported the window.postMessage method.

To read the text please click here

A summary of JavaScript cross-domain issues

Related Article

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.