10 different cross-domain solutions for JS

Source: Internet
Author: User

In client-side programming languages, such as JavaScript and ActionScript, the same-origin strategy is an important security concept that has important implications for securing data. The same-origin policy stipulates that scripts across domains are isolated, and one domain script cannot access and manipulate most of the properties and methods of another domain. So what is the same domain and what is a different domain?

Homologous policy

In client-side programming languages, such as JavaScript and ActionScript, the same-origin strategy is an important security concept that has important implications for securing data. The same-origin policy stipulates that scripts across domains are isolated, and one domain script cannot access and manipulate most of the properties and methods of another domain. So what is the same domain and what is a different domain? When two domains have the same protocol (such as HTTP), the same ports (such as 80), the same host (for example), then we can think of them as the same domain. For example, and is the same domain, and,,, any two of them will form a cross-domain. The same-origin policy should also handle special cases, such as restricting access to scripts under the file protocol. The local HTML file in the browser is opened through the file protocol, if the script can be accessed through the file protocol to any other files on the hard disk, there will be a security risk, the current IE8 still have such a hidden danger.

Cross-domain resource sharing is constrained by the same-origin policy. But with the practice of people and the progress of the browser, there are many valuable experiences in the cross-domain request of the skills of precipitation and accumulation. Here I divide the cross-domain resource sharing into two types, one-way data request, and the other is two-way message communication. Next I'll list some common cross-domain approaches, and the source code for the following cross-domain instances can be obtained from here.

  One-way cross-domain

JSONP

JSONP (JSON with Padding) is a simple and efficient cross-domain approach where script tags in HTML can load and execute JavaScript from other domains, so we can dynamically load resources from other domains with the script tag. For example, I want to load domain B's data from page PageA of Domain A, then in the page pageb of domain B I declare the data required PageA in JavaScript, and then load the PageB in PageA with the script tag. Then the script in the PAGEB will be executed. Jsonp adds a callback function on this basis, PAGEB executes the function defined in PageA after loading, and the required data is passed to the function as an argument. JSONP is easy to implement, but there are some security implications, and if a third-party script executes arbitrarily, it can tamper with the page content and intercept sensitive data. But Jsonp is the right choice for passing data on both sides of a trusted side.

Flash URLLoader

Flash has its own set of security policies that can be used by the server to declare which domain SWF files can be accessed by the Crossdomain.xml file, and SWF can also use the API to determine which domain SWF it can load. When accessing resources across domains, such as data from a domain request domain, we can use Flash to send HTTP requests. First, modify the crossdomain.xml on the domain (typically stored in the root directory if you do not need to create it manually) and add the whitelist. Second, send HTTP requests via Flash Urlloader, and finally pass the response results to JavaScript via the Flash API. Flash Urlloader is a common cross-domain solution, but if you need to support iOS, there's nothing you can do about it.

Access Control

Access control is more than a cross-domain approach and is currently supported in only a few browsers that can send a cross-domain HTTP request (Firefox, Google chrome, etc. via XMLHttpRequest, IE8 is implemented by Xdomainrequest), the requested response must contain a Access-control-allow-origin HTTP response header that declares the accessibility of the requesting domain. For example, the asset.php sends a cross-domain HTTP request, then asset.php must include the following response header:

Header ("Access-control-allow-origin:");

Window.name

The Name property of the Window object is a very special property, and when the window's location changes and then reloads, its Name property can remain unchanged. Then we can load the other domain's page B with an IFRAME in page A, While Page B uses JavaScript to assign the data to be passed to Window.name,iframe after loading, page a modifies the address of the IFRAME, changes it to an address in the same domain, and then reads out the value of the window.name. This approach is ideal for one-way data requests, and the protocol is simple and secure. External scripts are not executed as JSONP.

Server Proxy

When the data provider does not provide support for the JSONP protocol or the Window.name protocol, and there is no open access to other domains, we can crawl the data through the server proxy. For example, when a page under a domain requires a resource file Asset.txt under request, sending a direct AJAX request to/asset.txt is definitely blocked by the browser. At this point, we are under a proxy, and then bind the AJAX request to this proxy path, such as/proxy/, and then this agent sends HTTP request access under the Asset.txt, cross-domain HTTP requests are on the server side, the client does not produce cross-domain AJAX requests. This cross-domain approach does not require an agreement with the target resource and is aggressive, and it is also important to note that the agent should be protected in practice, such as restricting the use or frequency of use by others.

  Bidirectional cross-domain

Document.domain

By modifying the domain property of document, we can communicate between domains and subdomains or different subdomains. The same domain policy considers that domains and subdomains belong to different domains, for example, and Su is a different domain, and we cannot invoke the JavaScript method defined in Su in the next page. But when we change the domain property of their document to A.com, the browser will think that they are in the same domain, then we can call each other's method to communicate.

Fim–fragment Identitier Messaging

Between different domains, JavaScript can only do very limited access and operation, in fact, we use these limited access rights to achieve cross-domain communication purposes. FIM (Fragment identitier Messaging) was invented on this premise. The parent window can read and write URLs to the IFRAME, and the IFRAME can read and write to the parent window's Url,url part is called Frag, which is the # number and the character behind it, which is generally used for browser anchor positioning, and the server side does not care about this part, It should be said that the HTTP request does not carry frag, so this part of the modification will not produce an HTTP request, but will produce a browser history. The principle of FIM is to change the frag part of the URL for two-way communication. Each window sends a message by changing the location of the other window, and receives the message by listening for changes to its own URL. This way of communication will cause some unnecessary browser history, and some browsers do not support Onhashchange event, need polling to know the URL changes, finally, the URL in the browser has a length limit, which restricts the amount of data transferred each time.

Flash LocalConnection

Two-way communication on the page can also be resolved by Flash, which has the LocalConnection class in the Flash API that allows two SWF to communicate through the process, where the SWF can be played in a standalone Flash player or air. It can also be embedded in an HTML page or in a PDF. Following this communication principle, we can nest a SWF in different domain HTML pages to achieve the purpose of passing data to each other. SWF Exchange data through LocalConnection is very fast, but each time the amount of data has a size limit of 40kb. In this way to cross-domain communication is too complex, and requires 2 SWF files, the practicality is not strong.

Window.postmessage

Window.postmessage is a very new approach to HTML5 definition, and this method can easily communicate across windows. Because it is a very new method, it is not available in very old and older browsers.

Cross Frame

Cross Frame is a variant of FIM that uses a blank iframe, does not generate redundant browser history, and does not require a change in the polling URL, making a big difference in usability and performance. The rationale for this is roughly the assumption that there is a page a.html on the domain and a blank proxy page proxya.html, There is a page b.html and a blank proxy page on the other domain proxyb.html,a.html when a message needs to be sent to b.html, the page creates a hidden iframe, The src of the iframe points to proxyb.html and the message as a URL frag, because b.html and proxyb.html are the same domain, so after the IFRAME loading is complete, b.html can obtain the URL of the IFRAME and then parse out Message, and remove the IFRAME. The same principle occurs when b.html needs to send a message to a.html. Cross frame is a good way to communicate in two directions, and it is safe and efficient, but it is not available in opera, but in opera we can use a simpler window.postmessage instead.

  Summarize

There are many ways to cross-domain, and we can find the most suitable solution for different application scenarios. For example, one-way data request, we should prefer JSONP or window.name, two-way communication we take the cross Frame, we can also use the server proxy to crawl the data without a communication agreement with the data provider.

Article reprinted from: http://www.educity.cn/wenda/53094.html

10 different cross-domain solutions for JS

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.