Common JavaScript cross-domain communication methods _javascript Tips

Source: Internet
Author: User
Tags script tag

This article mainly introduces several common JavaScript cross-domain communication methods. First, explain the JSONP.
1, JSONP
JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to solve the problem of Cross-domain data access for mainstream browsers. Because of the homology policy, Web pages that are generally located in server1.example.com cannot communicate with servers that are not server1.example.com, while HTML <script> elements are an exception. Using this open policy of <script> elements, Web pages can get JSON data generated dynamically from other sources, and this usage pattern is called JSONP. The data captured by JSONP is not JSON, but arbitrary JavaScript, executed using a JavaScript literal instead of parsing with the JSON parser.
below we introduce the concrete implementation of the JSONP.
We know that Web pages can be executed unconditionally even if the code in a Cross-domain JS file, of course, is compliant with Web script security policy. The remote server remoteserver.com has a remote.js file code below the root directory:
alert (' I am a remote file '); 
The local server localserver.com has a jsonp.html page code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 
 
 

There is no doubt that the page will pop up with a prompt form showing the success of Cross-domain calls.

Now we define a function on the jsonp.html page and then pass in the data in the remote Remote.js to invoke it. The jsonp.html page code is as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> 
 
 

The Remote.js file code is as follows:
Localhandler ({"Result": "I am remote JS bring data"});
Run successfully, it seems that the purpose of Cross-domain remote access to data is achieved, but another problem arises, how can I let remote JS know it should call the local function called what name? At this point we need to provide the service side of the JS script dynamically generated on the line, the caller can be used to tell the server what they need to function, jsonp.html code as follows:

 <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  
 

This time the code changes relatively large, no longer directly to the remote JS file to write dead, but the code to implement dynamic query, and this is the JSONP client implementation of the core, in this case the focus is on how to complete the JSONP call the whole process.
We see the URL in the call passed a code parameter, told the server I want to check the CA1998 flight information, and the callback parameter tells the server, my local callback function is called Flighthandler, so please pass the query results into this function to call. This page called flightresult.aspx generates a section of this code to provide to jsonp.html (server implementation Here is not demonstrated, and the language you choose is irrelevant, in the final analysis is stitching string):

Flighthandler ({" 
 code": "CA1998", 
 "price": 1780, 
 "tickets": 5 
}); 

Passed to the Flighthandler function is a JSON that describes the basic information about the flight. Run the page, the successful pop-up prompts the window, JSONP implementation of the entire process successfully completed!
But there is a problem with the JSONP that the remote server is responsible for wrapping the JSON data and invoking the named function, which is a security risk, and when using JSONP, you must fully trust the data provided by the server, and the malicious script can take over our application directly. So next we're going to introduce a different way to avoid this security risk.
2, CORS
CORS (Cross originresource sharing, cross source resource sharing) implements the cross source XMLHttpRequests, which includes a Origin header that provides the server with the source information for the HTTP request. The head is protected by the browser and cannot be changed by the application code. This approach is far more secure than evaluating external input.
Previous Ajax can only be homologous request, now through the xmlhttprequests level two, the Cross-domain request. Suppose our page or application is already on the http://www.test1.com, and we intend to extract the data from the http://www.test2.com request. In general, if we use AJAX directly to request will fail, the browser will also return the "Source mismatch" error, "Cross-domain" is the origin.
You can allow requests from http://www.test1.com by simply adding one header to the cors,http://www.test2.com. The PHP code is as follows:

Header ("access-comtrol-allow-origin:*"); <span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); > </span> 

where * indicates that any domain is allowed to submit requests to our server. You can also set the specified domain name as follows:

Header ("access-control-allow-origin:http://www.test2.com"); 

After you set up the header information, the other fields are ready to be requested.
The premise of using Cross-domain resource sharing is that browsers must support this feature, and the server side must agree to this "Cross-domain". If the above conditions are met, the code will be written in exactly the same way as a request that does not cross the domain.
Xhr.open (' Get ', ' http://www.test2.com ');
Next, we'll introduce another way to communicate in real time:
3, cross-document messaging
communicates across document information. With this feature, as long as you get to the page of the Window object instance, not only with the original Web page can communicate with each other, but also to achieve cross-domain communication. To accept the information sent from another window, you must listen for the OnMessage event of the Window object, and other windows can pass the data through the PostMessage method, which uses two parameters: the first argument is the message text that is sent, but it can also be any JS object. The second parameter is the URL address of the object window that receives the message.
The following test, the main page index.html code is as follows:

<! DOCTYPE html> 
 
 

The page referenced by the window other.html the following code:

<! DOCTYPE html> 
 
 

The test results are as follows:


You can see the communication on the other.html in the index.html and 8020 port servers in the 81-port server.
The complete code is as follows:

<! DOCTYPE html>
 
 

Crossdocumentmessaging_index.html

<! DOCTYPE html>
 
 

This is all in this article and I want to help you understand familiar JavaScript cross-domain communication methods.

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.