JavaScript cross-domain method rollup _javascript Tips

Source: Internet
Author: User
Tags script tag

Web development often requires cross-domain problems, and the root cause of cross-domain problems is the same homology strategy in browser security, for example, for http://www.a.com/1.html:

The 1.http://www.a.com/2.html are homologous;
2.https://www.a.com/2.html are different sources because of different protocols;
3.http://www.a.com:8080/2.html are different sources because of different ports;
4.http://sub.a.com/2.html are different sources because the hosts are different.

In the browser,<script>, , <iframe> and <link> tags are those that can load cross-domain (not homologous) resources, and are loaded in a way that is equivalent to a normal GET request. The only difference is that, for security reasons, browsers do not allow the ability to read and write to the loaded resource in this way, but only the capabilities that the label itself should have (such as script execution, style application, and so on).

The most common cross-domain problem is the problem of Ajax Cross-domain access, by default, Cross-domain URLs are inaccessible via Ajax. Here I'm documenting the cross-domain approach I've learned:

1. Server-side proxies , which have little to say, the disadvantage is that by default the service that receives the AJAX request is the IP and UA of the client that cannot be obtained.

2. IFrame, the use of IFRAME is equivalent to open a new Web page, the specific Cross-domain method is roughly, domain a opened the parent page nested a point to the domain B of the IFRAME, and then submit the data, after completion, B's server can:

Returns a 302 redirect response, returning the result back to a field;
Within this IFRAME, an IFRAME that points to a domain is nested.

Both of these eventually implement Cross-domain calls, which are functionally more powerful than the JSONP described below, because DOM operations and JavaScript calls to each other are fine after cross-domain, but there are some limitations, such as the result being passed as a URL parameter, This means that when the data volume is very large, it is troublesome to split the transmission, and there is a problem that the IFRAME itself brings, and the interaction of the parent page and the IFRAME itself has security limitations.

3. Using a script tag across domains , this approach is also common, with script tags that can load exotic JavaScript and execute, and interact with the parent page by pre-set callback functions. It has a name called Jsonp Cross-domain, and Jsonp is the Lou of JSON with padding. It's an unofficial protocol, obviously loading script, and why is it related to JSON? This is the callback function, there is a typical way to use it, is through the JSON to pass the parameter, the JSON data into the callback function, which is the meaning of Jsonp's json+padding.

There are many JSONP services on the Internet that provide data, essentially cross-domain requests, and specify good callback in the request URL, such as Callback=result, then automatically invoke the result function when the data is obtained. and pass the data in JSON, for example (search "Football"):

Http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=football&callback=result

Using jquery to Invoke is written as:

Copy Code code as follows:

$.getjson ("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=football&callback=?", Function ( Data) {
//...
});

In general, the limitation of JSONP's cross-domain approach is that you can only use GET requests, and you cannot solve the problem of how to make JavaScript calls between two pages in different domains.

4. Flash Cross domain:

It accesses the Crossdomain.xml file under the root directory of the target Web site to determine whether to allow this Cross-domain access, based on the contents of the file:

Copy Code code as follows:

<cross-domain-policy>
<allow-access-from domain= "xxx.xxx.com"/>
</cross-domain-policy>

5. IMG Tags can also be used , which is a very common method, the function is weak, can only send a GET request, there is no callback, Google's click Count is so determined.

6. Window. PostMessage, this is HTML5 's new mechanism for Cross-domain Communications, only Firefox 3, Safari 4, and IE8 and later versions support. Use it to send messages to other windows in the following way:

Copy Code code as follows:

Otherwindow.postmessage (message, targetorigin);

In the received window, you need to set up an event handler to receive the message sent over:
Copy Code code as follows:

Window.addeventlistener ("message", ReceiveMessage, false);
function ReceiveMessage (event) {
if (event.origin!== "http://example.org:8080")
Return
}

Note that you must use the origin and source properties of the message to verify the identity of the sender, or you may create an XSS vulnerability.

7. Access Control

There are browsers that support access-control-allow-origin such as the response headers, such as:

Copy Code code as follows:

Header ("access-control-allow-origin:http://www.a.com");

Allows cross-domain access to www.a.com is specified.

8. Window.name

It was actually used as a means of hacking, the essence of which is that when window location changes, the page reloads, but interestingly, the window.name does not change, so it can be used to transmit values. With the IFRAME, change a few times the window object of the IFRAME, complete the practical cross-domain data transfer.

9. Document.domain

This approach applies to cross-domain communication between a.example.com and b.example.com, because there is a common domain called example.com, as long as you set Document.domain to example.com, but if a.example1.co There is no way to communicate between M. and B.example2.com.

Fragment identitier Messaging (FIM)

This method is very interesting and requires the cooperation of IFRAME. Fragment identitier is the URL of the well number (#) often used for anchor location of the part, this part of the change will not cause page refresh, the Mother window can casually access the URL of the IFRAME, and the IFRAME can also casually access the Mother window URL, Then the communication can be realized by changing the fragmement identitier. The disadvantage is that changes in fragmement identitier produce unnecessary historical records and have length limitations, and some browsers do not support Onhashchange events.

Cross Frame (CF)

This method is a variant of the above FIM method, and the nature of CF and FIM is actually described in my "GWT First Experience" article (it's just used to implement history and rewind), it dynamically creates an invisible IFrame, points to an exotic, and after processing, The fragment identitier in the URL of this iframe contains processing results for the parent page to access, while the browser URL does not change.

COOKIE+P3P Agreement

Using the P3P protocol to access cookies across domains to achieve cross-domain access is also a singular trick. P3P is a privacy-protection recommendation published by the Consortium to provide privacy protection for Internet users who surf the internet. Set the cookie path to "/", that is, there is no domain restrictions, this time some browsers to allow other URLs to read the page, some are not allowed, in this case need to be in the parent page response to the head set P3P head:

Copy Code code as follows:

p3p:cp= "Cura ADMa DEVa Psao psdo our bus UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"

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.