Javascript cross-origin method, principles, and solutions to problems (detailed description) _ javascript skills

Source: Internet
Author: User
Tags subdomain
For security reasons, javascript does not allow cross-origin calls to objects on other pages. However, security restrictions also bring a lot of trouble to inject iframe or ajax applications. A simple understanding of cross-origin is that due to the restrictions of the javascript same-origin policy, javascript under the.com domain name cannot operate B .com or the object under the c.a.com domain name cross-origin access to javascript is a common problem for web developers, what is cross-origin? The Script loaded on one domain obtains or operates on the document attributes of another domain. The following three methods for implementing cross-origin javascript are listed:
1. implement cross-origin based on iframe

Cross-Domain implementation based on iframe requires that the two domains have the characteristics of aa.xx.com and bb.xx.com, that is, the two pages must belong to one basic domain (for example, both xxx.com and xxx.com.cn ), use the same protocol (for example, http) and the same port (for example, 80). In this way, add document. domain, you can call the sub-page function on the parent page. The Code is as follows:
Page 1:
Html code

   《script》  document.domain = "xx.com";  function aa(){   alert("p");  }  《script》      《script》  document.getElementById('i').onload = function(){   var d = document.getElementById('i').contentWindow;   d.a();  };  《script》    

Page 2:

Html code

    《script》  document.domain = "xx.com";  function a(){  alert("c");   }  《script》        

At this time, the parent page can call the function of the Child page to implement js cross-origin access.

2. implement cross-origin based on script tags

The script tag itself can access resources in other domains and is not restricted by the browser's same-source policy. You can dynamically create a script tag on the page. The Code is as follows:

Java code

var script = document.createElement('script'); script.src = "http://aa.xx.com/js/*.js?1.1.15"; document.body.appendChild(script); 

In this way, you can dynamically create a script tag to load js files in other domains, and then call the function of the loaded js file through this page, the defect in doing so is that documents in other domains cannot be loaded, but only js files can be used. jsonp is implemented in this way. jsonp passes a callback parameter to other domains, the callback parameter value and json string are packed into javascript Functions in the background of other domains to return the result. Because the request is sent through the script tag, the browser parses the returned string according to javascript, implements data transmission between domains.
Jsonp support in jquery is also based on this solution.

3. Background proxy

This method can solve all cross-domain problems, that is, to forward requests from other domains to the background of the domain, the background of this domain accesses other domains by simulating an http request, and then returns the returned results to the foreground. The advantage of this is that no matter the document is accessed, or JavaScript files can be implemented across domains.

The following table shows the relativeHttp://store.company.com/dir/page.htmlResult of same-source detection:

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.

Conclusion:

In addition to the above methods, there are also cross-origin methods such as flash and proxy page setting on the server, which will not be described here.

The above four methods can be selected based on the actual situation of the project. the name method is neither complex nor compatible with almost all browsers. This is an excellent cross-origin method.

The above is all about the cross-origin javascript method, principles, and troubleshooting methods. I hope it will be helpful to you.

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.