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 Sharing
Cross-origin Resource Sharing defines how the browser communicates with the server when the cross-origin resource must be accessed.CORS
The 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 abovetrigkit4
Is relative path, if we want to useCORS
, RelatedAjax
The 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.
ForCORS
Mainly 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 formatJSON
A "usage mode" that allows a webpage to request information from another domain.
JSONP
It 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 useXMLHttpRequest
It 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>
jquery
A global function is automatically generated to replacecallback=?
After obtaining the data, it will be automatically destroyed, which is actually a temporary proxy function.$.getJSON
The method automatically determines whether to cross-origin. If it is not cross-origin, the commonajax
Method. 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:XMLHttpRequest
Object-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.JavaScript
Call 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 isiframe
Its src ishttp://example.com/b.html
Obviously, this page corresponds toiframe
The framework is in different domains, so we cannot get it by writing js Code on the page.iframe
Of:
<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.domain
It can be used.http://www.example.com/a.html
Andhttp://example.com/b.html
The 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.html
Set 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.html
Also 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.domain
The method is only applicable to the interaction between frameworks of different subdomains.
Use window. name for cross-Origin
window
The object hasname
Property. This property has a feature: In the lifecycle of a window, all pages loaded by the window sharewindow.name
, Each pagewindow.name
Both have read and write permissions,window.name
Is permanently present in all pages loaded by a window.
Use the HTML5 window. postMessage Method for cross-Origin
window.postMessage(message,targetOrigin)
The method ishtml5
New features can be usedwindow
Whether the window object belongs to the same or different sourceIE8+、FireFox、Chrome、Opera
And other browsers are supportedwindow.postMessage
Method.
Click here to read the text