Several practical principles of cross-domain method in JS

Source: Internet
Author: User
Tags script tag subdomain

The JS cross-domain refers to the data transfer or communication between different domains via JS, such as using AJAX to request data from a different domain, or by JS to get the frames (IFRAME) of the different domains in the page. As long as the protocol, domain name, and port are any different,

are considered to be different domains.

The following table shows the results of relative http://store.company.com/dir/page.html homology detection:

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

One, cross-domain through JSONP

In JS, it is not possible for us to request data from different domains directly with XMLHttpRequest. 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, there is a a.html page, the code inside it needs to use Ajax to obtain a different domain JSON data, assuming that the JSON data address is http://example.com/data.php, then the code in a.html can do this:

We see that the address that gets the data is followed by a callback parameter, which, by convention, is the name of the parameter, but you use the other as well. Of course, if the JSONP address page that gets the data is not your own control, you have to follow the rules of the party that provided the data.

format to manipulate it.

Because it is introduced as a JS file, so the http://example.com/data.php return must be an executable JS file, so the PHP code of this page may be this:

The result of the final page output is:

So the JS file obtained by http://example.com/data.php?callback=dosomething is the dosomething function we defined earlier, and its parameters are the JSON data we need, So we get the data we need across the domain.

So the principle of jsonp is very clear, through the script tag to introduce a JS file, this JS file loading success will execute our function specified in the URL parameters, and we will need to pass the JSON data as parameters. So Jsonp is the page that needs the server side

The corresponding mating of the surface.

Knowing the principle of Jsonp cross-domain, we can use JS to dynamically generate script tags for cross-domain operations, instead of deliberately manually writing those script tags. If your page uses jquery, it is easy to jsonp by wrapping it in a way that can

Have done.

The principle is the same, except that we do not need to manually insert the script tag and define the rollback function. jquery automatically generates a global function to replace the question mark in callback=, and then automatically destroys the data after it is acquired, in effect, a temporary proxy

The role of the number. The $.getjson method automatically determines whether a cross-domain, non-cross-domain, calls a normal Ajax method, or cross-domain, invokes the JSONP callback function in the form of an asynchronously loaded JS file.

2, by modifying the document.domain to cross the subdomain

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. One thing to note,

Between different frames (parent-child or peer), is able to get to each other's Window object, but the egg hurts is that you can't use the properties and methods of the retrieved window object (the PostMessage method in HTML5 is an exception, and some browsers such as IE6 can also

Using a few attributes such as top, parent, and so on, you can only get to a Window object that is almost useless. For example, there is a page, its address is http://www.example.com/a.html, in this page there is an IFRAME, it's

SRC is http://example.com/b.html, it is clear that this page and the IFRAME framework inside it is different domain, so we can not write in the page JS code to obtain the contents of the IFRAME:

This time, document.domain can come in handy, we just put http://www.example.com/a.html and http://example.com/ B.html the 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. For example: The document.domain of a document in a.b.example.com can be set to either a.b.example.com, b.example.com, or example.com, but cannot be set to C.a.b.example.com, because this is a subdomain of the current domain and cannot be set to baidu.com because the primary domain is already different.

Set document.domain in page http://www.example.com/a.html:

In the page http://example.com/b.html also set Document.domain, and this is also necessary, although this document's domain is example.com, However, you must also display the value of the setting Document.domain:

This allows us to access various properties and objects in the IFRAME via JS.

However, if you want to request the http://example.com/b.html page directly via Ajax in the Http://www.example.com/a.html page, Even if you set the same document.domain is still not good, so the method of modifying Document.domain only

The interaction between frameworks that apply to different subdomains. If you want to use AJAX methods to interact with different subdomains of the page, in addition to using the Jsonp method, you can also use a hidden iframe to do a proxy. The principle is to let this iframe load a with what you want to pass

Ajax gets the target page of the data in the same domain page, so the page in this IFRAME can normally use Ajax to get the data you want, and then through the method we have just said to modify document.domain, so that we can through JS completely control the

An IFRAME so that we can get the IFRAME to send an AJAX request, and then we can get the data we received.

3. Use Window.name for cross-domain

The Window object has a Name property that has a feature: that is, within the lifetime of a window, All the pages loaded in the window are shared by a window.name, each page has read and write permissions to Window.name, and Window.name is held

There is a long list of all pages loaded in a window and will not be reset due to the loading of the new page.

For example: There is a page a.html, it has such code:

Then look at the code for the b.html page:

A.html page loading 3 seconds, jump to the b.html page, the result is:

We see that on the b.html page, we successfully obtained the value of the previous page a.html to Window.name set. If after all the loaded pages are not modified Window.name, then all of these pages get the Window.name value

Are the values that are set on the A.html page. Of course, if necessary, any one of these pages can modify the value of Window.name. Note that the value of Window.name can only be the form of a string, the maximum size of this string can allow about 2M

To a larger capacity, depending on the browser, but generally enough.

In the above example, the pages a.html and b.html are in the same domain, but even if a.html and b.html are in different domains, the same conclusion applies, and this is the principle of cross-domain using Window.name.

Here's a look at how to get data across domains through Window.name. or an example.

For example, there is a www.example.com/a.html page, you need to a.html the page JS to get another page located in different fields www.cnblogs.com/data.html data.

The code in the Data.html page is very simple, which is to set the current window.name to the data value that the A.html page wants to get. The code in data.html:

So in the A.html page, how do we load the data.html page into it? Obviously we can't load the data.html page directly on the a.html page by changing the window.location, because we want to get the data in data.html even if the a.html page doesn't jump. The answer is to use a hidden iframe in the a.html page to act as a man-in-the-middle character, to get data.html data from the IFRAME, and then a.html to get the data that the IFRAME gets.

An IFRAME that acts as a middleman wants to get to Data.html's data through Window.name, just set the SRC to www.cnblogs.com/data.html. Then a.html want to get the data obtained by the IFRAME, that is, want to get the window.name of the IFRAME value, you must also set the IFRAME src to the same domain as the a.html page, otherwise, according to the same homologous strategy, a.html is not accessible to the IFRAME of the Window.name property. This is the entire cross-domain process.

Look at the code for the a.html page:

The above code is just the simplest principle of the demo code, you can use the JS package above the process, such as the dynamic creation of the IFRAME, dynamic registration of various events and so on, of course, for security, after obtaining data, you can also destroy the IFRAME as a proxy. There are a lot of similar out-of-the-box code on the Internet, which is interesting to look for.

Cross-domain through Window.name, that's it.

4. Use the newly introduced Window.postmessage method in HTML5 to transfer data across domains

The Window.postmessage (Message,targetorigin) method is a newly introduced feature of HTML5 that can be used to send messages to other window objects, regardless of whether the window object belongs to the same origin or different source, currently ie8+, Browsers such as FireFox, Chrome, and opera already support the Window.postmessage method.

The Window object that invokes the PostMessage method refers to the window object that receives the message, the first parameter of the method is the message to be sent, and the type can only be a string The second parameter, Targetorigin, is used to qualify the domain of the Window object that receives the message, and if you do not want to qualify the domain, you can use the wildcard character *.

The window object that needs to receive the message, but receives the message by listening to its own message event, which is stored in the event object's Data property.

As mentioned above, sending a message to another window object is actually a case where a page has several frames, because each frame has a window object. In discussing the second approach, we have said that the frames of different domains can be obtained from each other's window object, and you can also use the Window.postmessage method. Let's look at a simple example with two pages

The results we get when we run a page:

We see the B page successfully received the message.

The use of PostMessage to transfer data across domains is more intuitive and convenient, but the disadvantage is that IE6, IE7 does not support, so the use of the need to decide according to actual needs.

Conclusion:

In addition to the above several methods, there are flash, on the server set proxy page, such as cross-domain mode, here do not introduce.

The above four methods, according to the actual situation of the project to choose the application, the individual think Window.name method is not complex, but also compatible to almost all browsers, this is a very good cross-domain approach.

Several practical principles of cross-domain method in JS

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.