Explanation of the four methods and principles of javascript cross-Origin

Source: Internet
Author: User
Tags subdomain

The following table shows the result of the same source test as http://store.company.com/dir/page.html:

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

1. Cross-origin through jsonp

In js, we cannot directly use XMLHttpRequest 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, if there is an a.html page, the code in it needs to use ajax to obtain json data in different domains. Assume that the json data address is http://example.com/data.php, then the code in a.html can be like this:

We can see that there is a callback parameter next to the address for obtaining data. This parameter name is used by convention, but the same applies to other parameters. Of course, if you cannot control the jsonp address page for data retrieval, you must follow the prescribed format of the data provider.

Because it is introduced as a js file:

The output result of the page is:

So through http://example.com/data.php? Callback = The js file obtained by dosomething is the previously defined dosomething function, and its parameter is the json data we need, so that we can obtain the data we need across domains.

In this way, the jsonp principle is clear. A js file is introduced through the script tag. After the js file is loaded successfully, the function specified in the url parameter will be executed, the json data we need is passed in as a parameter. Therefore, jsonp requires the server-side pages to be matched accordingly.

After knowing the cross-origin principle of jsonp, we can use js to dynamically generate script tags for cross-origin operations, instead of manually writing those script tags. If jquery is used on your page, jsonp operations can be easily performed through its encapsulation method.

The principle is the same, but we do not need to manually insert the script tag and define the function to return. Jquery automatically generates a global function to replace callback =? After obtaining the data, it will be automatically destroyed, which is actually a temporary proxy function. $. The getJSON method automatically determines whether the cross-origin function is used. If the cross-origin method is not used, the common ajax method is called. If the cross-origin method is used, the jsonp callback function is called in the form of Asynchronously loading js files.

2. 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. It must be noted that different frameworks (Parent and Child or their peers) can obtain window objects of each other, however, you cannot use the properties and methods of the obtained window object (the postMessage method in html5 is an exception, some browsers, such as ie6, can also use a few attributes such as top and parent. In short, you can get only one useless window object. For example, there is a page where its address is http://www.example.com/a.html, there is an iframe in this page, its src is a http://example.com/ B .html, obviously, this page is different from the iframe framework in it, so we cannot get the content in iframe by writing js code in the page:

At this time, document. domain can be used, we just need to http://www.example.com/a.html and http://example.com/ B .htmlthe two pages of document.domainare 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. For example, the document of a document in a. B .example.com. domain can be set to either a. B .example.com, B .example.com, or example.com, but it cannot be set to c.a. B .example.com because it is a subdomain of the current domain and cannot be set to baidu.com because the primary domain is different.

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

Document. domain is also set in the page http://example.com/ B .html, and this is also required, although the domain of this document is example.com, but it must be displayed to set the value of document. domain:

In this way, we can access various attributes and objects in iframe through js.

But if you want to directly request the http://www.example.com/a.html page via ajax in the http://example.com/ B .html page, even if you set the same document. domain still does not work, So modify document. the domain method is only applicable to the interaction between frames of different subdomains. If you want to use ajax to interact with pages of different subdomains, you can use a hidden iframe as a proxy in addition to the jsonp method. The principle is to make this iframe load a page in the same domain as the target page for obtaining data through ajax, therefore, the pages in the iframe can normally use ajax to obtain the data you want, and then modify the document as we just mentioned. the domain method allows us to completely control this iframe through js, so that we can let iframe send ajax requests, and then we can get the data we receive.

3. Use window. name for cross-Origin

The window object has a name attribute, which has a feature: In the lifecycle of a window, all pages loaded by the window share a window. name, each page on the window. all names have read and write permissions, window. name is permanently stored in all pages loaded by a window and will not be reset due to loading of the new page.

For example, a webpage a.html contains the following code:

Let's look at the B .html Page code:

A.html page 3 seconds after being loaded, the B .html page is displayed. The result is:

We can see that a.html on the B .html page successfully obtained the value set for window. name on the previous page. The value set on the hosts page. If necessary, you can modify the value of window. name on any page. Note that the value of window. name can only be a string. the maximum size of this string can be 2 MB or even larger. It depends on different browsers, but it is generally enough.

In our example, the pages a.htmland B .htmlare used in the same domain, but a.htmland B .html are in different domains. The above conclusions are also applicable, which is exactly the principle of cross-domain using window. name.

Next, let's take a look at how to use window. name to retrieve data across domains. For example.

For example, a worker.

The Code on the data.html page is very simple. You can set the expected data value for the.html page to the previous example. Code in data.html:

In the.html page, can we load the data.html page? Shard. Then obtain the data obtained by iframe.

Iframeof the person in the center wants to obtain the data set by data.html through window. name. You only need to set the src of this iframe to www.cnblogs.com/data.html. Secret cannot access the window. name attribute in iframe. This is the entire cross-origin process.

See the code on the.html page:

The above code is just the simplest principle to demonstrate the code. You can encapsulate the above process with js, such as dynamically creating iframe, dynamically registering various events, and so on. Of course, for security, after obtaining the data, you can also destroy the iframe as the proxy. There are also a lot of similar off-the-shelf code on the Internet. If you are interested, you can find it.

Cross-origin through window. name.

4. Use the newly introduced window. postMessage method in html5.

Window. the postMessage (message, targetOrigin) method is a new feature of html5. it can be used to send messages to other window objects, whether the window object is of the same or different origins, currently, IE8 +, FireFox, Chrome, Opera, and other browsers all support windows. postMessage method.

The window object that calls the postMessage method is the window object that receives the message. The first parameter message of this method is the message to be sent, and the type can only be a string; the second parameter targetOrigin is used to limit the domain of the window object that receives the message. If you do not want to limit the domain, you can use the wildcard *.

The window object that needs to receive messages. However, you can listen to your own message events to obtain the transmitted messages. The message content is stored in the data attribute of the event object.

The above-mentioned message sending to other window objects refers to the situation where a page has several frameworks, because each framework has a window object. When discussing the second method, we said that the frameworks of different domains can obtain the window objects of the other party, and the window. postMessage method can also be used. The following is a simple example with two pages.

The result is as follows:

We can see that the message is successfully received on page B.

It is more intuitive and convenient to use postMessage for cross-Origin data transmission, but the disadvantage is that IE6 and IE7 are not supported, so you do not need to decide based on your actual needs.

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.