JavaScript cross-domain summarization and solutions (turn) __java

Source: Internet
Author: User


What is Cross-domain 1, document.domain+iframe Setup 2, dynamically creating script 3, cross-domain data transfer with IFRAME and Location.hash 4, Window.name, 5, using HTML5 postMessage 6, the use of flash

This article is from the network (http://f2e.me/200904/cross-scripting/, the site is no longer accessible), only for personal reading notes, and slightly modified and supplemented. What is cross-domain

JavaScript is not allowed to call objects on other pages across domains for security reasons. But it also brings a lot of trouble to injecting IFRAME or AJAX applications at the same time as security restrictions. Here's a quick way to sort through some of the questions that involve Cross-domain:

First what is Cross-domain, simply understand that because JavaScript is the same as the restrictions of the same policy, a.com domain name JS can not operate B.Com or c.a.com domain name under the object. A more detailed description can be seen in the following table:

URL Description whether to allow communication
Http://www.a.com/a.js
Http://www.a.com/b.js
Under the same domain name Allow
Http://www.a.com/lab/a.js
Http://www.a.com/script/b.js
Different folders under the same domain name Allow
Http://www.a.com:8000/a.js
Http://www.a.com/b.js
Same domain, different port Not allowed
Http://www.a.com/a.js
Https://www.a.com/b.js
Same domain, different protocol Not allowed
Http://www.a.com/a.js
Http://70.32.92.74/b.js
Domain name and domain name corresponding IP Not allowed
Http://www.a.com/a.js
Http://script.a.com/b.js
Primary domain is the same, subdomain is different Not allowed
Http://www.a.com/a.js
Http://a.com/b.js
Same domain name, different level two domain name (IBID.) Not allowed (cookies do not allow access in this case)
Http://www.cnblogs.com/a.js
Http://www.a.com/b.js
Different domain names Not allowed
Special attention to two points: first, if the protocol and port caused by cross-domain problem "front desk" is powerless, second: on cross-domain issues, domains are identified only by the "header of the URL" and do not try to determine whether the same IP address corresponds to two domains or two domains on the same IP.
"Header of a URL" refers to Window.location.protocol +window.location.host, which can also be understood as "Domains, protocols and Ports match".

Next, a simple summary of the "front" in general to deal with Cross-domain approach, background Proxy This scenario involves background configuration, here is not elaborated, interested can see Yahoo this article: "Javascript:use a Web Proxy for Cross-domain XMLHttpRequest Calls " 1, Document.domain+iframe set

Examples of the same primary domain and different subdomains can be resolved by setting up a Document.domain method. The specific approach is to add document.domain = ' a.com ' to the two documents in Http://www.a.com/a.html and http://script.a.com/b.html respectively. And then through the a.html file to create an IFRAME to control the contentdocument of the IFRAME, so that two JS files can be "interactive". Of course this method can only solve the primary domain is the same and two domain name different situation, if you whimsical to the script.a.com Domian set as Alibaba.com that is obviously will be the error. The code is as follows:

Www.a.com on the a.html document.domain = ' a.com '; var IFR = document.createelement (' iframe '); ifr.src = ' http://script.a.com/ B.html '; ifr.style.display = ' None ';d ocument.body.appendChild (IFR); ifr.onload = function () {var doc = ifr.contentdocument | | Ifr.contentWindow.document; Here manipulates b.html alert (doc.getelementsbytagname ("H1") [0].childnodes[0].nodevalue);

Script.a.com on the b.html document.domain = ' a.com ';

This approach applies to any page in {www.kuqin.com, kuqin.com, script.kuqin.com, css.kuqin.com} to communicate with each other.

Note: The domain default for a page is equal to Window.location.hostname. The main domain name is the domain name without www, for example a.com, the main domain name prefix is usually two level domain name or multi-level domain name, for example, www.a.com is actually a level two domain name. Domain can only be set as the primary domain name, you cannot set domain to c.a.com in b.a.com. Problem: 1, security, when one site (b.a.com) is attacked, another site (c.a.com) will cause security vulnerabilities. 2, if a page to introduce multiple IFRAME, to be able to operate all IFRAME, you must have to set the same domain. 2. Create script dynamically

Although the browser prohibits Cross-domain access by default, it does not prohibit the use of JS files that refer to other domains in the page, and it is free to perform function (including action cookies, Dom, and so on) in the introduced JS file. This makes it easy to achieve full cross-domain communication by creating a script node. The specific procedure may refer to Yui's get Utility

It is interesting to judge whether the script node is loaded or not: IE can only pass the script's ReadyStateChange attribute, and the other browser is the script load event. The following are some of the methods used to determine the completion of script loading. Js.onload = Js.onreadystatechange = function () {if (!this.readystate | | | this.readystate = = ' Loaded ' | | this.readystate = = = ' complete ') {//callback here to execute js.onload = Js.onreadystatechange = null;}}; 3. Using IFRAME and Location.hash

This method is more winding, but it can solve the problem of footstep replacement in the case of complete cross domain. The principle is to use Location.hash to carry out the value. In the Url:http://a.com#helloword ' #helloworld ' is location.hash, changes the hash does not cause the page to refresh, therefore may use the hash value to carry on the data transmission, certainly the data capacity is limited. If the domain name a.com under the file cs1.html to and cnblogs.com domain name under the cs2.html transmission information, cs1.html first create a hidden iframe,iframe of SRC to point to the cnblogs.com domain name cs2.html page, then H The ash value can be used for parameter passing. Cs2.html responds to the request and then passes the data by modifying the cs1.html hash value (since two pages are not in the same domain ie, Chrome is not allowed to modify the value of Parent.location.hash, so it is possible to modify it with the help of an agent Iframe;firefox under the a.com domain name. At the same time, add a timer on the cs1.html, at intervals to determine whether the value of Location.hash has changed, a little change to get the hash value. The code is as follows:

First a.com file cs1.html file: function startrequest () {var IFR = document.createelement (' iframe '); ifr.style.display = ' none '; IFR.SRC = ' Http://www.cnblogs.com/lab/cscript/cs2.html#paramdo '; Document.body.appendChild (IFR);} function Checkhash () {try {var data = Location.hash? location.hash.substring (1): '; if (console.log) {console.log (' N ow the data is ' +data '; The catch (e) {};} SetInterval (Checkhash, 2000);

cs2.html under cnblogs.com domain name://Simulate a simple parameter processing operation switch (location.hash) {case ' #paramdo ': CallBack (); break; case ' #paramset ':/ /do something ... break; function CallBack () {try {parent.location.hash = ' somedata ';} catch (E) {//IE, Chrome's security mechanism cannot modify parent.location.hash,// So to use a middle cnblogs domain under the agent iframe var ifrproxy = document.createelement (' iframe '); Ifrproxy.style.display = ' None '; IFRPROXY.SRC = ' Http://a.com/test/cscript/cs3.html#somedata '; Note that the file is Document.body.appendChild (ifrproxy) under the "A.com" field; }}

A.com domain name cs3.html//Because parent.parent and itself belong to the same domain, you can change its location.hash value Parent.parent.location.hash = Self.location.hash.substring (1);

Of course, there are many shortcomings, such as data directly exposed to the URL, data capacity and type are limited, etc. ... 4, Window.name implementation of cross-domain data transfer

The article is longer listed here is not easy to read, please see Window.name implementation of cross-domain data transfer. 5. Use HTML5 postMessage

One of the coolest new features in HTML5 is the transmission of cross document messaging across document messages. The next-generation browsers will support this feature: Chrome 2.0+, Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, and Safari 4.0+. Facebook has already used this feature to support web-based real-time messaging with PostMessage. Otherwindow.postmessage (message, targetorigin); Otherwindow: A reference to the window that receives the information page. Can be the Contentwindow property of the IFrame in the page, the return value of the window.open, and the value that is fetched from the Window.frames by name or subscript.
Message: The data to be sent, string type.
Targetorigin: Used to limit Otherwindow, "*" means no restrictions

Code in a.com/index.html: <iframe id= "IFR" src= "b.com/index.html" ></iframe><script type= "text/" JavaScript ">window.onload = function () {var IFR = document.getElementById (' IFR '); var targetorigin = ' http://b.com '; /if written ' http://b.com/c/proxy.html ' effect AS//if written ' http://c.com ' will not perform postMessage ifr.contentWindow.postMessage (' I was there! ', targetorigin); </script>

Code in b.com/index.html: <script type= "Text/javascript" > Window.addeventlistener (' Message ', function (event) {/ The Origin property is used to determine the message source address if (Event.origin = = ' http://a.com ') {alert (event.data);//Eject "I was there!" alert (Event.source); References to Window objects in. com, index.html//But because of the homology policy, here Event.source cannot access the Window object}, False);</script>

Reference article: "Proficient in HTML5 Programming" fifth chapter--cross document message mechanism, Https://developer.mozilla.org/en/dom/window.postmessage 6, use Flash

This is the method seen from the YUI3 IO component, specifically visible http://developer.yahoo.com/yui/3/io/.
You can see more Cross-domain agent file specifications in Adobe Developer connection: ross-domain Policy file specifications, HTTP Headers blacklist.

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