JavaScript cross-domain method

Source: Internet
Author: User
Tags script tag

This article mainly introduces several common JavaScript cross-domain communication methods. First, explain the JSONP.

JSONP

JSONP (JSON with Padding) is a "usage pattern" of JSON that can be used to address cross-domain data access issues in mainstream browsers. Because of the same-origin 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 strategy of <script>, the Web page can get JSON data that is dynamically generated from other sources, and this usage pattern is called JSONP. The data captured with JSONP is not JSON, but arbitrary JavaScript, which executes with a JavaScript interpreter instead of parsing with a JSON parser.

Let's introduce the concrete implementation of the next JSONP.

We know that even if the code in the cross-domain JS file (which is, of course, conforms to the Web Scripting Security Policy), the Web page can be executed unconditionally. The remote server remoteserver.com root directory has a remote.js file code as follows:

Alert (' I am a remote file ');

There is a jsonp.html page code below the local 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 the page will pop up a prompt form that shows cross-domain invocation success.
Now we define a function on the jsonp.html page and then pass in the data in the remote Remote.js to make the call. 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 the data brought by remote JS"});

Running successfully, it seems that the purpose of the cross-domain remote data acquisition is implemented, but another problem arises, how can I let remote js know what the local function it should call the name of it ? In this case, we need to dynamically generate the JS script provided by the server, and the caller can tell the server what function they need by using the 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 core part of the JSONP client implementation, the focus of this example is how to complete the JSONP call the whole process.

We see a code parameter passed in the URL of the call, telling the server that I'm looking for CA1998 flight information, while the callback parameter tells the server that my local callback function is called Flighthandler, so please pass the query results into this function for invocation. This page called flightresult.aspx generates a piece of code that is provided to jsonp.html (the server-side implementation is not demonstrated here, regardless of the language you choose, the final word is stitching the strings):

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

Passed to the Flighthandler function is a JSON that describes the basic information of the flight. Run the page, the successful pop-up prompt window, JSONP implementation of the entire process completed successfully!

However, there is a problem with JSONP, that is, the remote server is responsible for wrapping the JSON data, and calling the named function, there is a security risk, in the use of JSONP, you must fully trust the data provided by the server, malicious script can directly take over our application. So let's introduce a different way to avoid this security risk.

CORS

CORS (cross originresource sharing, across-source resource sharing) implements cross-origin xmlhttprequests, and cross-origin HTTP requests include an Origin header, which provides the server with source information for HTTP requests. 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 requested from the same origin, and now cross-domain requests are made through xmlhttprequests level two. 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 "source mismatch" error, "cross-domain" is also the origin.

With cors,http://www.test2.com, you can allow requests from http://www.test1.com by simply adding a 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>

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

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

Once the header information is set, the other domains are ready for the request.

The premise of using cross-domain resource sharing is that the browser must support this feature, and the server side must agree to this "cross-domain". If the above conditions are met, the code is written exactly like a request that does not cross a domain.

Xhr.open (' GET ', ' http://www.test2.com ');
Next, we introduce another kind of real-time communication method:

cross-document Messaging

Cross-Document information communication. Using this feature, you can communicate with the original Web page, as long as you get an instance of the Window object that the Web page is in, and cross-domain communication is possible. To accept information sent from other windows, you must listen to the OnMessage event of the Window object, and other windows can pass the data through the PostMessage method, which uses two parameters: the first parameter is the text of the message being sent, but it can 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 other.html code for the page referenced by the window is as follows:
<! DOCTYPE html>
The test results are as follows:

You can see traffic in the index.html and 8020 port servers in the 81 port server for other.html.


The complete code is as follows:














JavaScript cross-domain method

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.