Summary of 10 cross-origin sharing methods in JavaScript

Source: Internet
Author: User
Tags subdomain

JavaScriptFor security reasons, it is not allowed to call objects on other pages across domains. Cross-origin is restricted by the JavaScript same-origin policy. In client programming languages such as javascript and ActionScript, the same-source policy is a very important security concept, which has an important significance in ensuring data security. The same-origin policy specifies that scripts in different domains are isolated. scripts in one domain cannot access and operate most of the attributes and methods in another domain. Next, let's take a look at the cross-sharing approach.

Same-origin policy

In client programming languages such as javascript and ActionScript, the same-source policy is a very important security concept, which has an important significance in ensuring data security. The same-origin policy specifies that scripts in different domains are isolated. scripts in one domain cannot access and operate most of the attributes and methods in another domain. So what is the same domain and what is different domain? When two domains have the same protocol (such as http), the same port (such as 80), and the same host such as, we can think that they are the same domain. For example. The same-origin policy should also handle some special situations, such as limiting the access permissions of scripts under the file protocol. Local HTML files are opened through the file protocol in the browser. If the script can access any other files on the hard disk through the file protocol, security risks may occur, at present, IE8 still has such risks.

Cross-origin Resource Sharing is restricted by the same-origin policy. However, with the development of practices and browsers, we have gained a lot of valuable experience in cross-origin request skills. Here I divide cross-origin Resource Sharing into two types: one is one-way data requests and the other is two-way message communication. Next, I will list some common cross-origin methods. The source code of the following cross-origin instances can be obtained from here.

Unidirectional cross-Origin

JSONP (JSONwithPadding) is a simple and efficient cross-origin method. The script tag in HTML can load and execute javascript in other domains, so we can dynamically load resources in other domains through script tags. For example, if I want to load the data of Domain B from the pageA page of Domain A, then in the pageB page of Domain B, I declare the data required by pageA in the form of JavaScript, then, in pageA, use the script tag to load pageB, and the script in pageB will be executed. JSONP adds a callback function. After pageB loads the function, it executes the function defined in pageA. The required data is passed to the function in the form of parameters. JSONP is easy to implement, but it also has some security risks. If a third-party script is executed at will, it can tamper with the page content and intercept sensitive data. However, JSONP is a perfect choice for both trusted Parties to transmit data.

Flash has its own security policy. The server can use crossdomain. an xml file is used to declare which domains can be accessed by SWF files. SWF can also use APIs to determine which domains can be loaded by SWF files. When cross-origin resource access, for example, requests data from the domain to the domain www. B .com, we can use flash to send HTTP requests. First, modify crossdomain. xml on the domain www. B .com (usually stored in the root directory, if not manually created) and add TO THE whitelist. Second, send an HTTP request through FlashURLLoader, and finally pass the response result to JavaScript through Flash API. FlashURLLoader is a common cross-origin solution. However, if you need to support iOS, this solution is powerless.

The name attribute of the window object is a very special attribute. When the location of the window changes and is reloaded, its name attribute can remain unchanged. In this case, we can use iframe to load page B of other domains in page A, while in page B, we use JavaScript to assign the data to window. after name and iframe are loaded, page A modifies the iframe address and changes it to an address in the same domain. Then the window can be read. the value of name. This method is suitable for one-way data requests, and the protocol is simple and secure. External scripts are not executed without restrictions like JSONP.

When the data provider does not support the JSONP protocol or the window. name protocol, or has no access permission to other domains, we can use serverproxy to capture data. For example, when a user requests the resource file asset.txt under, an ajaxrequest directed to www. B .com/asset.txtwill be blocked by the browser. At this time, we configure a proxy under, and then bind the Ajax request to this proxy path, such. This cross-origin method does not need to sign agreements with the target resource and is aggressive. In addition, it should be noted that the proxy should be protected to a certain extent in practice, such as limiting the use or frequency of others.

Bidirectional cross-Origin

By modifying the domain attribute of the document, we can communicate between the domain and the subdomain or different subdomains. The same domain policy assumes that the domain and subdomain belong to different domains. For example, and are different domains. At this time, we cannot call the JavaScript method defined in on the page under But when we change the domain attribute of their document to, the browser will think that they are in the same domain, then we can call each other's method to communicate with each other.

JavaScript can only perform limited access and operations between different domains. In fact, we can use these limited access permissions to achieve cross-origin communication. FIM (FragmentIdentitierMessaging) was invented on this premise. The parent window can perform URL reading and writing on iframe, and iframe can also read and write the URL of the parent window. A part of the URL is called frag, which is the # and its subsequent characters. It is generally used for browser anchor location, the Server does not care about this part. It should be said that the HTTP request process will not carry frag, so this part of modification will not generate HTTP requests, but will generate browser history records. The FIM principle is to change the URL's frag for bidirectional communication. Each window sends messages by changing the location of other windows, and listens for changes in its own URL to receive messages. This communication method may cause unnecessary browser history records. In addition, some browsers do not support the onhashchange event. You need to poll the changes to the URL. Finally, the URL has a length limit in the browser, this restricts the amount of data transferred each time.

Two-way communication on the page can also be solved through Flash. The Flash API has the LocalConnection class, which allows two SWF to communicate through processes. In this case, SWF can be played in an independent Flash Player or AIR, it can also be embedded in HTML pages or PDF files. Following this communication principle, we can nest a SWF on the HTML pages of different domains to transfer data to each other. SWF exchange data quickly through LocalConnection, but each time the data volume has a size limit of 40 kb. Cross-origin communication using this method is too complex and requires two SWF files, which is not practical.

Window. postMessage is a new method defined in html5. this method can easily communicate across windows. Because it is a new method, it cannot be used in both old and old browsers.

In general, there are many cross-origin methods. We can find the most suitable solution for different application scenarios. For example, for one-way data requests, we should prioritize JSONP or window. name, two-way communication we adopt CrossFrame. In the absence of a communication protocol with the data provider, we can also use serverproxy to capture data.

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: 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.