JavaScript cross-origin problem summary, javascript cross-Origin

Source: Internet
Author: User

JavaScript cross-origin problem summary, javascript cross-Origin
What is cross-origin?

Concept: as long as the Protocol, domain name, and port are different, they are regarded as different domains.

URL instructions whether communication http://www.a.com/a.jshttp://www.a.com/ B .js is allowed under the same domain name allow different folders under the same domain name allow http://www.a.com/lab/a.jshttp://www.a.com/script/ B .js: 8000/. jshttp: // www.a.com/ B .js the same domain name, different ports do not allow the same http://www.a.com/a.jshttps://www.a.com/ B .js 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 not allow the same 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 of the same domain name, different second-level domain names (same as) are not allowed (cookie in this case is not allowed to access) http://www.cnblogs.com/a.jshttp://www.a.com/ B .js of different domain names are not allowed

Different ports and protocols can only be solved through the background.

Cross-origin Resource Sharing (CORS)

CORS(Cross-Origin Resource SharingCross-origin Resource Sharing defines how the browser communicates with the server when the cross-origin resource must be accessed.CORSThe basic idea behind it is to use a custom HTTP header to allow the browser to communicate with the server, so as to determine whether the request or response should succeed or fail.

<script type="text/javascript">    var xhr = new XMLHttpRequest();    xhr.open("GET", "/trigkit4",true);    xhr.send();</script>

The abovetrigkit4Is relative path, if we want to useCORS, RelatedAjaxThe code may be as follows:

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

The difference between the Code and the previous Code is that the relative path is replaced with the absolute path of other domains, that is, the interface address for cross-origin access.

ForCORSMainly by settingAccess-Control-Allow-Origin. If the browser detects the corresponding settings, Ajax can be allowed for cross-origin access.

To solve cross-origin problems, we can use the following methods:

Cross-origin through jsonp

What's the problem? What isjsonp? Wikipedia defines:JSONP(JSON with Padding)Yesdata formatJSONA "usage mode" that allows a webpage to request information from another domain.

JSONPIt is also called the filling JSON. It is a new method for applying JSON, but it is only the JSON that is included in the function call. For example:

callback({"name","trigkit4"});

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

In js, we useXMLHttpRequestIt is not allowed to request data in different domains. However, it is possible to introduce js script files in different domains on the page, and jsonp is implemented by using this feature. For example:

<Script type = "text/javascript"> function dosomething (jsondata) {// process the obtained json data} </script> <script src = "http://example.com/data.php? Callback = dosomething "> </script>

After the js file is loaded successfully, the function specified in the url parameter will be executed, and the json data we need will be passed in as the parameter. Therefore, jsonp requires the server-side pages to be matched accordingly.

<? Php $ callback = $ _ GET ['callback']; // GET the callback function name $ data = array ('A', 'B', 'C '); // echo $ callback. '('. json_encode ($ data ). ')'; // output?>

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

If jquery is used on your page, jsonp operations can be easily performed through its encapsulation method.

<Script type = "text/javascript"> $. getJSON ('HTTP: // example.com/data.php? Callback = ?, Function (jsondata) ') {// process the obtained json data}); </script>

jqueryA global function is automatically generated to replacecallback=?After obtaining the data, it will be automatically destroyed, which is actually a temporary proxy function.$.getJSONThe method automatically determines whether to cross-origin. If it is not cross-origin, the commonajaxMethod. If the cross-origin method is used, it is called in the form of Asynchronously loading js files.jsonp.

Advantages and disadvantages of JSONP

JSONP has the following advantages:XMLHttpRequestObject-implemented Ajax requests are subject to same-origin policy restrictions. They have better compatibility and can be run in older Browsers without the support of XMLHttpRequest or ActiveX; after the request is complete, you can call callback to return the result.

The disadvantage of JSONP is that it only supports GET requests but not POST and other types of HTTP requests. It only supports cross-origin HTTP requests, it cannot solve how two pages in different domains are implemented.JavaScriptCall problems.

Comparison between CORS and JSONP

CORS is more advanced, convenient, and reliable than JSONP.

1. JSONP can only implement GET requests, while CORS supports all types of HTTP requests.

2. With CORS, developers can use common XMLHttpRequest to initiate requests and obtain data, which provides better error handling than JSONP.

3. JSONP is mainly supported by old browsers, which often do not support CORS, but most modern browsers already support CORS ).

Cross-subdomain by modifying document. domain

Browsers all have a same-source policy. One of its limitations is that the first method we mentioned cannot request documents in different-source databases through ajax. Its second restriction is that JavaScript interaction cannot be performed between frames of different domains in the browser.

Different frameworks can obtain window objects, but cannot obtain corresponding properties and methods. For example, the address of a page ishttp://www.example.com/a.html, There isiframeIts src ishttp://example.com/b.htmlObviously, this page corresponds toiframeThe framework is in different domains, so we cannot get it by writing js Code on the page.iframeOf:

<Script type = "text/javascript"> function test () {var iframe = document. getElementById ('invalid ifame'); var win = document. contentWindow; // you can obtain the window object in iframe, but the properties and methods of this window object are almost unavailable var doc = win.doc ument; // The document Object var name = win in iframe cannot be obtained here. name; // The name attribute of the window object is also not obtained here} </script> <iframe id = "iframe" src = "http://example.com/ B .html" onload = "test () "> </iframe>

At this time,document.domainIt can be used.http://www.example.com/a.htmlAndhttp://example.com/b.htmlThe document. domain of these two pages can be set to the same domain name. However, there are limits on document. domain settings. We can only set document. domain to its parent domain or a higher level, and the primary domain must be the same.

1. On the pagehttp://www.example.com/a.htmlSet indocument.domain:

<Iframe id = "iframe" src = "http://example.com/ B .html" onload = "test ()"> </iframe> <script type = "text/javascript"> document. domain = 'example. com '; // set it to the primary domain function test () {alert (document. getElementById ('deleiframe '). contentWindow); // contentWindow obtains the window object of the subwindow.} </script>

2. on the pagehttp://example.com/b.htmlAlso setdocument.domain:

<Script type = "text/javascript"> document. domain = 'example. com '; // set document on the iframe load page. domain to match it with the document on the home page. same domain </script>

Modifydocument.domainThe method is only applicable to the interaction between frameworks of different subdomains.

Use window. name for cross-Origin

windowThe object hasnameProperty. This property has a feature: In the lifecycle of a window, all pages loaded by the window sharewindow.name, Each pagewindow.nameBoth have read and write permissions,window.nameIs permanently present in all pages loaded by a window.

Use the HTML5 window. postMessage Method for cross-Origin

window.postMessage(message,targetOrigin)The method ishtml5New features can be usedwindowWhether the window object belongs to the same or different sourceIE8+、FireFox、Chrome、OperaAnd other browsers are supportedwindow.postMessageMethod.

 

Click here to read the text

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.