JavaScript Cross-domain methods, principles, and problem-solving methods (detailed) _javascript skills

Source: Internet
Author: User
Tags http request json script tag


JavaScript cross-domain access is a common problem for web developers, what is Cross-domain, a script loaded on one domain Gets or operates a document property on another domain, and three implementations of JavaScript Cross-domain methods are listed below:
1. Cross-domain implementation based on IFRAME



Cross-domain requirements based on IFRAME implementation The aa.xx.com,bb.xx.com feature is that two pages must belong to an underlying domain (for example, all xxx.com, or xxx.com.cn), using the same protocol (for example, all HTTP) and the same port (for example, all are 80) so that you can add document.domain to the two pages and then implement the function of the parent page calling the child page, as follows:
Page One:
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> 


 
 


Page Two:



HTML code


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


At this time, the parent page can call the child page a function, to achieve the JS Cross-domain access



2. Implementing Cross-domain based on the script label



The script label itself has access to resources from other domains, is not limited by the browser's homology policy, and can be created dynamically by creating a script label on the page, as follows:



Java code


var script = document.createelement (' script '); 
SCRIPT.SRC = "Http://aa.xx.com/js/*.js"; 


So by dynamically creating a script tag can load other domain JS files, and then through this page can be called after the Load JS file function, the flaw is not to load other domain documents, can only be JS file, Jsonp is achieved by this way, Jsonp by passing in a callback parameter to another domain, wrapping the callback parameter value and the JSON string into a JavaScript function back through the background of the other domain, because the request is made through the script label, The browser will parse the returned string into JavaScript to implement the data transfer between the field and the domain.
The support for JSONP in jquery is also based on this scenario.



3. The Backstage proxy way



This approach solves all cross-domain problems, that is, the background as a proxy, every time a request to another domain is forwarded to the background of the domain, the background of the domain is accessed by simulating an HTTP request to the other domain, returning the returned results to the foreground, and the benefit is that both the document being accessed and the JS file can be implemented across the domain.



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





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



I. Cross-domain through JSONP



In JS, we are not able to request data from different domains directly with XMLHttpRequest. However, it is possible to introduce a JS script file on a different domain on the page, and JSONP is using this feature to achieve it.



For example, there's a a.html page that uses Ajax to get JSON data from a different domain, assuming that the JSON data address is http://example.com/data.php, then the code in a.html can do this:






We see that there is also a callback parameter behind the address where the data is obtained, as is customary with this parameter name, but you use the same as the other. Of course, if the JSONP address page that gets the data is not in your own control, it has to be done according to the specified format of the party providing the data.



Because it is as a JS file to introduce, so http://example.com/data.php return must be a can execute the JS file, so this page of the PHP code may be like this:






The final result of that page output is:






So the JS file obtained by http://example.com/data.php?callback=dosomething is the dosomething function we defined before, 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 loaded successfully will execute our URL parameters specified in the function, and will we need the JSON data as parameters passed in. So JSONP is the server side of the page to match the corresponding.



Knowing the principle of jsonp cross-domain, we can use JS to dynamically generate script tags for cross-domain operation, instead of intentionally manually writing those script tags. If your page uses jquery, it can be easily jsonp by the method it encapsulates.






The principle is the same, except that we do not need to manually insert the script tag and define the callback function. jquery automatically generates a global function to replace the question mark in callback=, then automatically destroys it after it gets the data, which is actually a temporary proxy function. The $.getjson method automatically determines whether Cross-domain, not cross-domain, calls the normal Ajax method, and then invokes the JSONP callback function in the form of asynchronously loading the JS file.



Second, by modifying document.domain to cross subdomains



Browsers have a homologous policy, and one of the limitations is that in the first approach, we can't ask for documents from different sources in an AJAX way. Its second limitation is that there is no JS interaction between frames in different domains in the browser. One thing to note is that different frameworks (parent-child or sibling) are able to get to each other's window objects, but the egg hurts you but you can't use the properties and methods of the Window object you get (the PostMessage method in HTML5 is an exception, Some browsers, such as IE6, can also use a few attributes, such as top, parent, and so on, in short, you can only get an almost useless window object. For example, there is a page, its address is http://www.example.com/a.html, in this page there is an IFRAME, its src is http://example.com/b.html, obviously, This page is different from the IFRAME frame inside it, so we can't get the things in the IFRAME by writing the JS code in the page:






This time, document.domain can come in handy, we just put http://www.example.com/a.html and http://example.com/ B.html These two pages of the document.domain are set to the same domain name on it. Note, however, that the document.domain settings are limited, and we can only set the document.domain to a parent domain of its own 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 the domain of this document is example.com, However, the value of the setting Document.domain must be displayed:






So we can access the various properties and objects in the IFRAME through JS.



But 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, it doesn't work, so the method of modifying Document.domain only works with the interaction between the frameworks of different subdomains. If you want to use AJAX methods to interact with the pages of different subdomains, in addition to using the Jsonp method, you can also use a hidden iframe as a proxy. The idea is to have this iframe load a page in the same domain as the target page you want to get the data through Ajax, so the page in the IFRAME can use Ajax to get the data you want, Then we have just talked about modifying the Document.domain method, so that we can completely control the IFRAME through JS, so we can let the IFRAME to send AJAX requests, and then receive the data we can get.



Iii. using Window.name to cross-domain



The Window object has a Name property that has a feature: in the life cycle of a window (Windows), All the pages loaded in the window are shared by a window.name, each page has read and write permission to the Window.name, Window.name is persisted in all pages that have been loaded in a window and will not be reset by the load of the new page.



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






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






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






We saw the value on the B.html page that was successfully fetched to the Window.name set on its previous page a.html. If all of the downloaded pages are not modified by window.name, then all of the window.name values for these pages are the A.html page settings. Of course, if necessary, any one of these pages can modify the value of the window.name. Note that the value of the window.name can only be in the form of a string, the size of which allows for a maximum of 2M or even a larger capacity, depending on the browser, but generally enough.



In the example above, the pages we use a.html and b.html are in the same domain, but even if a.html and b.html are in different domains, the conclusion is also applicable, which is the principle of using Window.name to cross domain.



Let's take a look at the specific how to get data across domains through Window.name. or an illustrative example.



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



The code in the Data.html page is simple enough to give the current window.name the value of the data that the A.html page wants. Code in the data.html:






So how do we load the data.html page in the a.html page? Obviously we can't load the data.html page directly in 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 middleman, to get data.html data from the IFRAME, and then a.html to get the data that the IFRAME gets.



The iframe that acts as a middleman wants to obtain the data that data.html through the window.name set, only need to set this iframe src to www.cnblogs.com/data.html on the line. Then a.html want to get the data of the IFRAME, that is, to get the window.name value of the IFRAME, you must also set the SRC to the same domain as the a.html page, otherwise, according to the same homologous strategy mentioned above, a.html can not access to the IFRAME 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 demo code, you can use JS encapsulation of the above process, such as dynamic create IFRAME, dynamic registration of various events and so on, of course, in order to secure, after the acquisition of data, you can also destroy as an agent of the IFRAME. There are a lot of similar ready-made code on the Internet, interested can go to find out.



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



Iv. using the newly introduced Window.postmessage method in HTML5 to transfer data across domains



The Window.postmessage (Message,targetorigin) method is HTML5 new introduced feature that can be used to send messages to other window objects, regardless of whether the window object belongs to a homologous or different source, currently ie8+, Firefox, Chrome, opera and other browsers have supported the window.postmessage approach.



The Window object that calls the PostMessage method is the window object to receive the message, the first argument of the method is the message to send, 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 you can use the wildcard character * If you do not want to qualify the domain.



The window object that needs to receive the message, but by listening to its own message event to obtain the messages that are passed in, the message contents are stored in the Data property of the event object.



Sending messages to other Window objects, as mentioned above, actually refers to the case where a page has several frames, because each frame has a window object. When we discussed the second approach, we said that the frames of different domains were able to get to each other's window objects, and you could also use the Window.postmessage method. Let's look at a simple example with two pages









The results we get when we run page A:






We saw the B page successfully received the message.



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



Conclusion:



In addition to the above several methods, there are flash, on the server set proxy page, such as Cross-domain way, here is not introduced.



The above four methods can be based on the actual situation of the project to choose applications, personally think that the Window.name method is not complex, but also compatible with almost all browsers, this is an excellent Cross-domain method.



The above is this article introduces JavaScript Cross-domain method, principle and the problem solves the whole content of method, hope to be helpful to everybody.


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.