Summarizing the problem of JavaScript cross-domain and its solution

Source: Internet
Author: User

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 to indicate whether to allow traffic
Http://www.a.com/a.js
Http://www.a.com/b.js the same domain name allows

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 the same domain name, different ports are not allowed

Http://www.a.com/a.js
Https://www.a.com/b.js the same domain name, different protocols are 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, child domain is different not allowed

Http://www.a.com/a.js
Http://a.com/b.js the same domain name, different level two domain name (IBID.) is not allowed (cookies in this case also do not allow access)

Http://www.cnblogs.com/a.js
Http://www.a.com/b.js different domain names are not allowed

special attention to two points:

First, if the cross domain problem caused by the protocol and the port is "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, the Document.domain+iframe setting

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 for Alibaba.com that is obviously will be the error! The code is as follows:

The a.html on the www.a.com

Document.domain = ' a.com ';
var IFR = document.createelement (' iframe ');
IFR.SRC = ' http://script.a.com/b.html ';
Ifr.style.display = ' None ';
Document.body.appendChild (IFR);
Ifr.onload = function () {
var doc = Ifr.contentdocument | | Ifr.contentWindow.document;
To manipulate b.html here.
Alert (Doc.getelementsbytagname ("H1") [0].childnodes[0].nodevalue);
};

The b.html on the script.a.com

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 a 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 is here to perform
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 the file cs1.html file under a.com:

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 (' Now ', the data is ' +data ');
}
catch (e) {};
}
SetInterval (Checkhash, 2000);

Cs2.html under the cnblogs.com domain name:

Simulate a simple parameter-handling operation
Switch (Location.hash) {
Case ' #paramdo ':
CallBack ();
Break
Case ' #paramset ':
Do something ...
Break
}

function CallBack () {
try {
Parent.location.hash = ' Somedata ';
catch (e) {
The security mechanism of IE and chrome cannot modify Parent.location.hash,
So to use a proxy iframe in the middle of the cnblogs domain
var ifrproxy = document.createelement (' iframe ');
Ifrproxy.style.display = ' None ';
IFRPROXY.SRC = ' Http://a.com/test/cscript/cs3.html#somedata '; Note that the file is under the "a.com" field
Document.body.appendChild (Ifrproxy);
}
}

A.com under the domain cs3.html

Because Parent.parent and itself belong to the same domain, you can change the value of its Location.hash
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 as ' http://b.com/c/proxy.html ' effect
If you write ' http://c.com ', you won't execute postmessage.
Ifr.contentWindow.postMessage (' I was there! ', targetorigin);
};
</script>

Code in b.com/index.html:

<script type= "Text/javascript" >
Window.addeventlistener (' message ', function (event) {
To determine the message source address by Origin property
if (Event.origin = = ' http://a.com ') {
alert (event.data); Pop "I was there!"
alert (Event.source); References to Window objects in A.com, index.html
But because of the homology policy, the window object is not accessible here Event.source
}
}, False);
</script>

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

6, the use of 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.

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.