Home > Web Front-end > JS Tutorial > JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

WBOY
Release: 2016-05-16 15:46:57
Original
1256 people have browsed it

Javascript cross-domain access is a problem that web developers often encounter. What is cross-domain? A script loaded on one domain obtains or operates document attributes on another domain. Three methods for implementing JavaScript cross-domain are listed below. :
1. Cross-domain implementation based on iframe

Cross-domain implementation based on iframe requires that the two domains have the characteristics of aa.xx.com, bb.xx.com, that is, the two pages must belong to a basic domain (for example, both xxx.com, or xxx .com.cn), use the same protocol (for example, both are http) and the same port (for example, both are 80). In this way, adding document.domain to both pages at the same time can realize the function of the parent page calling the child page. The code is as follows :
Page 1:
Html code

<html> 
<head> 
 <script> 
 document.domain = "xx.com"; 
 function aa(){ 
  alert("p"); 
 } 
 </script> 
</head> 
<body> 
 <iframe src="http://localhost:8080/CmsUI/2.html" id="i"> 
 </iframe> 
 <script> 
 document.getElementById('i').onload = function(){ 
  var d = document.getElementById('i').contentWindow; 
  d.a(); 
 }; 
 </script> 
 </body> 
</html> 
Copy after login

Page 2:

Html code

<html> 
 <head> 
 <script> 
 document.domain = "xx.com"; 
 function a(){ 
 alert("c"); 
  } 
 </script> 
 </head> 
 <body> 
 </body> 
</html> 
Copy after login

At this time, the parent page can call the a function of the child page to achieve js cross-domain access

2. Cross-domain implementation based on script tags

The script tag itself can access resources in other domains and is not restricted by the browser's same-origin 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"; 
document.body.appendChild(script); 
Copy after login

In this way, js files from other domains can be loaded by dynamically creating script tags, and then the function of the loaded js file can be called through this page. The disadvantage of this is that documents from other domains cannot be loaded, only js files. jsonp is implemented in this way. jsonp passes a callback parameter to other domains, and packages the callback parameter value and json string into a javascript function through the background of other domains and returns it. Because the request is made through the script tag, the browser The returned string will be parsed and executed according to JavaScript, realizing data transmission between domains.
The support for jsonp in jquery is also based on this solution.

3.Backend proxy method

This method can solve all cross-domain problems, that is, the backend is used as a proxy, and each request for other domains is transferred to the backend of this domain. The backend of this domain accesses other domains by simulating http requests, and then returns The result is returned to the front desk. The advantage of this is that whether it is a document or a js file being accessed, it can be cross-domain.

The following table gives the relative http://store.company.com/dir/page.htmlResults of homology detection:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

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

1. Cross-domain via jsonp

In js, it is not possible to directly use XMLHttpRequest to request data on different domains. However, it is possible to introduce js script files from different domains on the page. jsonp uses this feature to achieve it.

For example, there is an a.html page. The code in it needs to use ajax to obtain json data on a different domain. Assume that the json data address is http://example.com/data.php, then the code in a.html can be like this:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

We see that there is a callback parameter after the address to obtain the data. By convention, this parameter name is used, but you can use other parameters as well. Of course, if the jsonp address page for obtaining data is not under your control, you must operate in accordance with the format specified by the party that provides the data.

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

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

The final output result of that page is:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

So the js file obtained through http://example.com/data.php?callback=dosomething is the dosomething function we defined before, and its parameters are the json data we need. In this way we get the data we need across domains.

In this way, the principle of jsonp is very clear. A js file is introduced through the script tag. After the js file is successfully loaded, it will execute the function we specified in the url parameter and pass in the json data we need as a parameter. . Therefore, jsonp requires corresponding cooperation from the server-side page.

After knowing the principle of jsonp cross-domain, we can use js to dynamically generate script tags for cross-domain operations without having to manually write those script tags. If your page uses jquery, you can easily perform jsonp operations through its encapsulated method.

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

The principle is the same, except that we don’t need to manually insert script tags and define callback functions. jQuery will automatically generate a global function to replace the question mark in callback=?, and then automatically destroy it after obtaining the data. In fact, it acts as a temporary proxy function. The $.getJSON method will automatically determine whether it is cross-domain. If it is not cross-domain, it will call the ordinary ajax method; if it is cross-domain, it will call the jsonp callback function in the form of asynchronously loading the js file.

2. Cross subdomains by modifying document.domain

Browsers all have a same-origin policy, and one of its limitations is that in the first method, we said that you cannot use ajax to request documents from different sources. Its second limitation is that js cannot interact between frames in different domains in the browser. One thing that needs to be explained is that different frameworks (father and son or peers) can obtain each other's window objects, but the annoying thing is that you cannot use the properties and methods of the obtained window objects (the postMessage method in HTML5 is an exception, and some browsers such as ie6 can also use a few attributes such as top and parent). In short, you can think of it as only getting an almost useless window object. For example, there is a page whose address is http://www.example.com/a.html , and there is an iframe in this page, and its src is http://example .com/b.html, obviously, this page and the iframe inside it are in different domains, so we cannot get the content in the iframe by writing js code in the page:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

At this time, document.domain can come in handy. We only need to add http://www.example.com/a.html and http://example.com/ b.htmlJust set the document.domain of these two pages to the same domain name. But it should be noted that the setting of document.domain is limited. We can only set document.domain to itself or a higher-level parent domain, and the main domain must be the same. For example: the document.domain of a document in a.b.example.com can be set to any one of a.b.example.com, b.example.com, and example.com, but it cannot be set to c.a.b.example.com because this is the current The subdomain of the domain cannot be set to baidu.com because the main domain is no longer the same.

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

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

Also set document.domain in the page http://example.com/b.html, and this is also necessary. Although the domain of this document is example.com, it still must be displayed. Set the value of document.domain:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

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

But if you want to directly request http://example.com/b.html through ajax in the http://www.example.com/a.html page Page, even if you set the same document.domain, it still won't work, so the method of modifying document.domain is only applicable to the interaction between frames in different subdomains. If you want to interact with pages in different subdomains through the ajax method, in addition to using the jsonp method, you can also use a hidden iframe as a proxy. The principle is to let this iframe load a page in the same domain as the target page you want to get data through ajax, so the page in this iframe can use ajax to get the data you want normally, and then through us The method of modifying document.domain just mentioned allows us to fully control this iframe through js, so that we can let the iframe send an ajax request, and then we can also obtain the received data.

3. Use window.name for cross-domain

The window object has a name attribute, which has a characteristic: that is, within the life cycle of a window (window), all pages loaded by the window share a window.name, and each page has a unique relationship with the window. name has read and write permissions. window.name is persistent in all pages loaded in a window and will not be reset when a new page is loaded.

For example: there is a page a.html, which has this code:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

Look at the code of the b.html page again:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

3 seconds after the a.html page was loaded, it jumped to the b.html page, and the result was:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

We see that the value set for window.name by its previous page a.html was successfully obtained on the b.html page. If window.name is not modified in all subsequent loaded pages, then the value of window.name obtained by all these pages will be the value set by the a.html page. Of course, if necessary, any of the pages can modify the value of window.name. Note that the value of window.name can only be in the form of a string. The maximum size of this string can allow a capacity of about 2M or more, depending on different browsers, but it is generally sufficient.

In the above example, the pages a.html and b.html we used are in the same domain, but even if a.html and b.html are in different domains, the above conclusion is also applicable. This This is also the principle of using window.name for cross-domain.

Let’s take a look at how to obtain data across domains through window.name. Or give an example.

For example, if there is a www.example.com/a.html page, you need to use the js in the a.html page to get another page www.cnblogs.com located on a different domain. The data in /data.html.

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

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

So in the a.html page, how do we load the data.html page? Obviously we cannot directly load the data.html page by changing the window.location in the a.html page, because we want to get the data in data.html even if the a.html page does not jump. The answer is to use a hidden iframe in the a.html page to act as a middleman. The iframe gets the data from data.html, and then a.html gets the data from the iframe.

If the iframe acting as a middleman wants to obtain the data set by window.name in data.html, it only needs to set the src of this iframe to www.cnblogs.com/data.html. Then if a.html wants to get the data obtained by the iframe, that is, if it wants to get the value of the window.name of the iframe, it must also set the src of the iframe to the same domain as the a.html page. Otherwise, according to the previous Regarding the same-origin policy, a.html cannot access the window.name attribute in the iframe. This is the entire cross-domain process.

Look at the code of the a.html page:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

The above code is just the simplest principle demonstration code. You can use js to encapsulate the above process, such as dynamically creating iframes, dynamically registering various events, etc. Of course, for the sake of safety, after obtaining the data, you can Destroy the iframe acting as a proxy. There are many similar ready-made codes on the Internet. If you are interested, you can look for them.

Cross-domain is done through window.name, that’s how it works.

4. Use the window.postMessage method newly introduced in HTML5 to transmit data across domains

window.postMessage(message,targetOrigin) method is a newly introduced feature of HTML5. You can use it to send messages to other window objects, regardless of whether the window object belongs to the same origin or different origins. Currently, IE8, FireFox, Chrome, Browsers such as Opera already support the window.postMessage method.

The window object that calls the postMessage method refers to the window object that wants to receive 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 reception. The domain where the window object of the message is located. If you don’t want to limit the domain, you can use the wildcard *.

The window object that needs to receive messages can obtain the incoming message by monitoring its own message event. The message content is stored in the data attribute of the event object.

Sending messages to other window objects mentioned above actually refers to the situation where a page has several frames, because each frame has a window object. When discussing the second method, we said that frameworks in different domains can obtain each other's window objects, and they can also use the window.postMessage method. Let’s look at a simple example with two pages

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

The result we got after running page a:

JavaScript cross-domain methods, principles and solutions to problems (detailed explanation)_javascript skills

We see that page b successfully received the message.

Using postMessage to transmit data across domains is relatively intuitive and convenient, but the disadvantage is that IE6 and IE7 do not support it, so whether to use it or not depends on actual needs.

Conclusion:

In addition to the above methods, there are also cross-domain methods such as flash and setting up proxy pages on the server, which will not be introduced here.

The above four methods can be selected and applied according to the actual situation of the project. I personally think that the window.name method is not complicated and is compatible with almost all browsers. This is really an excellent cross-domain method.

The above is the entire content of this article introducing the JavaScript cross-domain methods, principles and solutions to problems. I hope it will be helpful to everyone.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template