A summary of 10 ways to cross-domain sharing of javascript

Source: Internet
Author: User
Tags html page http request requires resource window domain access root directory

JavaScript is not allowed to call objects on other pages across domains for security reasons. Cross-domain is due to the limitations of the JavaScript homology policy. In the client programming language, such as JavaScript and ActionScript, the homology strategy is an important security concept that is important in ensuring data security. The homology policy stipulates that scripts across domains are isolated, and that a domain script cannot access and manipulate most of the properties and methods of another domain. Let's learn about ways to cross sharing.

Homology policy

In the client programming language, such as JavaScript and ActionScript, the homology strategy is an important security concept that is important in ensuring data security. The homology policy stipulates that scripts across domains are isolated, and that a domain script cannot access and manipulate most of the properties and methods of another domain. So what is called the same domain, what is different domain? When two domains have the same protocol (such as HTTP), the same ports (such as 80), and the same host (such as www.example.org), then we can assume that they are the same domain. For example, http://www.example.org/index.html and http://www.example.org/sub/index.html are the same domain, and http://www.example.org,https:// Any two of the www.example.org,http://www.example.org:8080,http://sub.example.org will form a cross-domain domain. Homology policies should also deal with special cases, such as restricting access to scripts under the file protocol. Local HTML file in the browser is opened through the file protocol, if the script can be accessed through the file protocol to other arbitrary files on the hard disk, there will be security risks, the current IE8 still have such a hidden danger.

Cross-domain resource sharing is constrained by the impact of homology policies. But with the practice of people and the progress of the browser, there are many valuable experiences in the technique of cross domain request. Here I divide cross-domain resource sharing into two types, one one-way data request and one two-way message communication. Next I'll list some common cross-domain ways in which the following Cross-domain instance source code can be obtained.

One-way cross-domain

JSONP (jsonwithpadding) is a simple and efficient cross-domain way in which script tags in HTML can load and execute JavaScript in other domains, so we can dynamically load resources from other domains through the script tag. For example, I'm going to load domain B from the page PageA of Domain A, so in the page pageb of domain B I declare pagea needed data in JavaScript, and then load PageB in PageA with a script tag, Then the script in the PAGEB will be executed. Jsonp The callback function is added on this basis, the function defined in PageA is executed after PageB loading, and the required data is passed to the function as a parameter. JSONP is easy to implement, but there are also some security risks, if the third party script arbitrary execution, then it can tamper with the content of the page, interception of sensitive data. But Jsonp is a very good choice for sending data across trusted parties.

Flash has its own set of security policies, the server can be crossdomain.xml file to declare which domain SWF file access, SWF can also through the API to determine which domain swf can be loaded. When accessing resources across domains, such as data from the domain www.a.com request domain www.b.com, we can use Flash to send HTTP requests. First, modify the crossdomain.xml on the domain www.b.com (generally stored in the root directory, if no need to manually create), add the www.a.com to the white list. Secondly, the HTTP request is sent via Flashurlloader, and finally, the response result is passed to JavaScript through FLASHAPI. Flashurlloader is a common cross-domain solution, but if you need to support iOS, there's nothing you can do about it.

The Window object's Name property is a very special property that, when the window's location changes and then reloads, its Name property can remain unchanged. Then we can load page B of the other domain with an IFRAME in page A, And in page B, using JavaScript to assign the data that needs to be passed to Window.name,iframe after loading, page a modifies the address of the IFRAME, turns it into an address in the same domain, and then reads the Window.name value. This method is very suitable for one-way data requests, and the protocol is simple and secure. Do not execute external scripts as Jsonp do without restrictions.

When the data provider does not provide support for the JSONP protocol or the WINDOW.NAME protocol or open access to other domains, we can crawl the data in a serverproxy way. For example, when a page under the www.a.com domain needs to request a www.b.com resource file asset.txt, sending a direct AJAX request to Www.b.com/asset.txt must be blocked by the browser. At this point, we have an agent under www.a.com and then bind the AJAX request to this proxy path, such as www.a.com/proxy/, This agent then sends HTTP request access to the Asset.txt under Www.b.com, the Cross-domain HTTP request is made on the server side, and the client does not produce a Cross-domain ajax request. This cross-domain approach requires no agreement with the target resources, aggression, and, in practice, a degree of protection for the agent, such as restrictions on the use or frequency of use by others.

Bidirectional cross-domain

By modifying the domain attribute of the document, we can communicate between domains and subdomains or different subdomains. The same domain policy considers domains and subdomains to be subordinate to different domains, such as www.a.com and sub.a.com, where we cannot invoke the JavaScript method defined in sub.a.com in a page under Www.a.com. But when we modify the domain attributes of their document to A.com, the browser thinks they are in the same domain, then we can call each other's method to communicate.

JavaScript can only do very limited access and operation between different domains, but we can use these limited access rights to achieve the purpose of cross-domain communication. FIM (fragmentidentitiermessaging) was invented under this premise. The parent window can read and write to the IFRAME, and the IFRAME can read and write the url,url of the parent window, which is called Frag, is the # and the character behind it, which is typically used for browser anchor positioning, and the server side does not care about this part, It should be said that the HTTP request will not carry frag, so this part of the modification will not produce HTTP requests, but will produce browser history. The principle of FIM is to change the frag part of the URL for two-way communication. Each window sends messages by changing the location of other windows, and receives messages by listening for changes to its own URLs. This way of communication will cause some unnecessary browser history, and some browsers do not support Onhashchange events, need to poll to learn the URL changes, and finally, the URL in the browser has a length limit, which restricts the amount of data transmitted each time.

Bidirectional communication on the page can also be solved by flash, which is localconnection in flashAPI, which allows the two SWF to communicate through the process, when the SWF can be played in a separate flashplayer or air, It can also be embedded in an HTML page or in a PDF. Following this communication principle, we can embed a SWF in each HTML page of different domains to achieve the goal of passing data to each other. SWF Exchange data through LocalConnection is very fast, but each time the amount of data has a 40kb size limit. In this way, cross-domain communication is too complex and requires 2 SWF files and is not practical.

Window.postmessage is a very new approach defined by HTML5, which is a convenient way to communicate across windows. Because it is a very new method, it is not available in both old and older browsers.

In general, there are a number of cross-domain approaches, and we can find the most appropriate solution for different scenarios. For example, one-way data requests, we should choose Jsonp or window.name, two-way communications we take the crossframe, in the absence of a communication agreement with the data provider, we can also use the Serverproxy way to crawl data.

"Edit Recommendation"

    1. How to handle large amounts of data in JavaScript
    2. 8 Web sites for stunning JavaScript effects
    3. Understanding of call and apply in JavaScript
    4. 16 Most popular JavaScript frameworks
"Responsible Editor: Qihappy TEL: (010) 68476606"


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.