Common javascript cross-origin communication methods

Source: Internet
Author: User

Common javascript cross-origin communication methods

This article mainly introduces several common cross-origin communication methods of javascript. First, let's explain JSONP.
1. JSONP
JSONP (JSON with Padding) is a "usage mode" of JSON, which can be used to solve cross-Origin data access problems in mainstream browsers. Because of the same-origin policy, web pages located in server1.example.com cannot communicate with servers that are not in server1.example.com, And the <script> element of HTML is an exception. Using the open policy of the <script> element, the webpage can obtain JSON data dynamically generated from other sources. This usage mode is called JSONP. The information captured with JSONP is not JSON, but arbitrary JavaScript. It is executed with a JavaScript literal interpreter instead of a JSON parser.
The following describes the specific implementation of JSONP.
We know that even the code in the Cross-origin js file (of course, that complies with the web script Security Policy) can be executed unconditionally on the web page. The remote server remoteserver.com root directory contains the following remote. js file code:
Alert ('am a remote file ');
The following figure shows the jsonp.html Page code of the worker server localserver.com:

<!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 a prompt form will pop up, showing that the cross-origin call is successful.

Now we define a function on the jsonp.html page, and then input data in remote. js for calling. 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 code of the remote. js file is as follows:
LocalHandler ({"result": "data from remote js "});
After successful running, it seems that cross-origin remote data retrieval is achieved, but another problem arises. How can I let remote js know the name of the local function that should be called? The pipeline 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 code changes a lot this time, instead of Directly Writing remote js files to death, but coding for dynamic query, which is also the core part of jsonp client implementation, the focus of this example is how to complete the entire jsonp call process.
We can see that a code parameter is passed in the called url, telling the server that I want to check information about the 98 flights, while the callback parameter tells the server that my local callback function is called flightHandler, therefore, pass the query results to this function for calling. The page calling flightresult.aspxgenerates the following code example to jsonp.html (the implementation of the server is not demonstrated here. It has nothing to do with the language you selected. In the end, it is a concatenation string ):

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

The flightHandler function is passed in json, which describes the basic flight information. Run the page. A Prompt window is displayed. The jsonp execution process is successfully completed!
However, the remote server is responsible for packaging json data and calling the naming function. This method has security risks. When using JSONP, you must fully trust the data provided by the server, malicious scripts can directly take over our applications. So next we will introduce another method to avoid this security risk.
2. CORS
CORS (Cross OriginResource Sharing) implements Cross-source XMLHttpRequests. Cross-source HTTP requests include an Origin header, which provides the server with the source information of HTTP requests. The header is protected by a browser and cannot be changed by application code. This method is far safer than evaluating external input.
In the past, ajax only allowed single-origin requests. Now, through XMLHttpRequests second-level, cross-origin requests can be made. Suppose that our page or application is already on the http://www.test1.com, and we intend to extract data from the http://www.test2.com request. Generally, If we directly use AJAX for requests, the browser will also return the error "Source mismatch", and "cross-origin" will be the same.
With CORS, The http://www.test2.com can allow requests from the http://www.test1.com by adding only one header. 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> 

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

header("Access-Control-Allow-Origin:http://www.test2.com"); 

After the header information is set, other domains can make requests.
The premise of "cross-origin Resource Sharing" is that the browser must support this function, and the server must agree to this "cross-origin ". If the preceding conditions are met, the code is written in the same way as a non-Cross-origin request.
Xhr. open ('get', 'http://www.test2.com ');
Next we will introduce another real-time communication method:
3. Cross-document messaging
Cross-document communication. To use this function, you only need to obtain an instance of the window object in which the webpage is located. It can not only communicate with the original web page, but also implement cross-origin communication. To accept information sent from other windows, you must listen to the onmessage event of the window object. Other windows can transmit data using the postmessage method. This method uses two parameters: the first parameter is the message text sent, but it can also be any js object. The second parameter is the url address of the Object window for receiving messages.
The code for index.html on the main page is as follows:

<! DOCTYPE html> 

The code of the page other.html used by the window is as follows:

<! DOCTYPE html> 

The test results are as follows:


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

<! DOCTYPE html> 

CrossDocumentMessaging_index.html

<! DOCTYPE html> 

The above is all the content in this article. I hope you will be familiar with common cross-origin javascript communication methods.

Articles you may be interested in:
  • Use of ajax jsonp for cross-origin requests
  • Jquery $. getJSON () Cross-origin request
  • Implementation of AJAX cross-origin request json data
  • Jquery ajax jsonp cross-origin call instance code
  • Jquery ajax cross-origin solution (json)
  • Implementation of jquery's ajax and getJson cross-origin acquisition of json data
  • Use jQuery and JSONP to easily solve cross-origin access problems
  • GetJSON cross-origin SyntaxError Analysis
  • Comparison of advantages and disadvantages of js cross-origin Problems and Solutions

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.