JavaScript cross-domain Summary and solutions

Source: Internet
Author: User
Tags subdomain

What is a cross-domain

1, the Document.domain+iframe setting

2. Create script dynamically

3. Using IFRAME and Location.hash

4, Window.name realization of cross-domain data transfer

5. Use HTML5 postMessage

6. Using Flash

This article is from the network (http://f2e.me/200904/cross-scripting/, which is inaccessible), only for personal reading notes, and slightly modified and supplemented.


What is a cross-domain

JavaScript is not allowed to invoke objects of other pages across domains for security reasons. But the security restrictions also bring a lot of trouble to inject IFRAME or AJAX applications. Here are some simple things to sort out about cross-domain issues:


First what is cross-domain, simple to understand is because of the JavaScript homologous policy limitations, a.com domain name JS can not operate B.Com or c.a.com under the domain name of the object. A more detailed explanation 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 name, different ports Not allowed
Http://www.a.com/a.js
Https://www.a.com/b.js
Same domain name, different protocols Not allowed
Http://www.a.com/a.js
Http://70.32.92.74/b.js
Domain 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 are also not allowed in this case)
Http://www.cnblogs.com/a.js
Http://www.a.com/b.js
Different domain names Not allowed


Pay special attention to two points:

First, if it is a cross-domain problem caused by protocol and port "front desk" is powerless,

Second: On a cross-domain issue, the domain is only identified by the "header of the URL" and does not attempt to determine whether the same IP address corresponds to two domains or two domains on the same IP.

The "header of the url" refers to Window.location.protocol +window.location.host, which can also be understood as "Domains, protocols and ports must match".

Then briefly summarize in the "front desk" generally handle cross-domain approach, background Proxy This scenario involves the 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

For examples where the primary domain is the same and the subdomain is different, it can be resolved by setting the Document.domain method. Specifically, the http://www.a.com/a.html and http://script.a.com/b.html two files can be added document.domain = ' a.com ' And then create an IFRAME in the a.html file to control the contentdocument of the IFRAME so that the two JS files can "interact" with each other. Of course, this approach can only solve the same primary domain and the two-level domain name is different, if you whimsical script.a.com Domian set to Alibaba.com that obviously will be 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;

Manipulating the 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 primary domain is a domain name without www, such as a.com, which is usually preceded by a two-level domain name or a multilevel domain name, such as Www.a.com, which is actually a two-level domain name. Domain can only be set as the primary domain name, and domain can not be set to c.a.com in B.a.com.


Problem:

1, security, when one site (b.a.com) is attacked, another site (c.a.com) can cause security vulnerabilities.

2, if a page to introduce multiple IFRAME, to be able to operate all the IFRAME, you must set the same domain.

2. Create script dynamically

Although the browser prohibits cross-domain access by default, it does not prohibit referencing other domain's JS files in the page, and can freely execute the function in the introduced JS file (including manipulating cookies, DOM, etc.). Based on this, it is convenient to create a script node to achieve complete cross-domain communication. Specific practice can refer to Yui's get Utility


It's pretty interesting to judge that the script node is loaded: IE can only pass the script's ReadyStateChange property, and the other browser is the Load event for the script. Here are some ways to determine the completion of script loading.


Js.onload = Js.onreadystatechange = function () {

if (!this.readystate | | this.readystate = = = ' Loaded ' | | this.readystate = = = ' complete ') {

Callback is executed here

Js.onload = Js.onreadystatechange = null;

}

};

3. Using IFRAME and Location.hash

This method is more round, but it can solve the problem of footstep replacement in the case of complete cross-domain. The principle is to use Location.hash to transmit values. In the Url:http://a.com#helloword ' #helloworld ' is location.hash, changing the hash does not cause the page to refresh, so you can use the hash value for data transfer, of course, the data capacity is limited. Assuming that the file under the domain name a.com cs1.html to and cnblogs.com the cs2.html of the domain name, cs1.html first creates a hidden iframe,iframe that automatically creates a cnblogs.com page under the cs2.html domain name The ash value can be used for parameter passing. The cs2.html responds to the request and then passes the data by modifying the hash value of the cs1.html (because two pages are not in the same domain ie, Chrome does not allow you to modify the value of Parent.location.hash, so you can modify it by using an agent Iframe;firefox under the a.com domain name. At the same time, add a timer on the cs1.html, interval time to determine whether the value of Location.hash has changed, a little change gets 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:


Simulates 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) {

IE, chrome security mechanism can not modify the Parent.location.hash,

So we're going 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);

}

}

The domain name under a.com cs3.html


Because Parent.parent and itself belong to the same domain, you can change the value of their 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 realization of cross-domain data transfer

There are three pages:

A.com/app.html: Application page.

a.com/proxy.html: Proxy file, which is usually an HTML file without any content, needs and applies the page under the same domain.

B.com/data.html: The page where the application page needs to get data, which can be called a data page.

The basic steps to implement are as follows:


Create an IFRAME in the Application page (a.com/app.html) and point its SRC to the data page (b.com/data.html).

The data page attaches the data to the window.name of the IFRAME, and the data.html code is as follows:

<script type= "Text/javascript" >

Window.name = ' I was there! '; Here is the data to be transferred, the size is generally 2m,ie and Firefox can be as large as about 32M

Data formats can be customized, such as JSON, string

</script>

In the App page (a.com/app.html), listen for the onload event of the IFRAME, which sets the src of this iframe to the proxy file for the local domain (the proxy file and the app page are in the same field, so you can communicate with each other). The app.html section code is as follows:

<script type= "Text/javascript" >

var state = 0,

iframe = document.createelement (' iframe '),

LOADFN = function () {

if (state = = = 1) {

var data = Iframe.contentWindow.name; Reading data

alert (data); Eject ' I was there! '

} else if (state = = = 0) {

state = 1;

Iframe.contentWindow.location = "http://a.com/proxy.html"; Set the proxy file

}

};

IFRAME.SRC = ' http://b.com/data.html ';

if (iframe.attachevent) {

Iframe.attachevent (' Loadfn);

} else {

Iframe.onload = LOADFN;

}

Document.body.appendChild (IFRAME);

</script>

Get the data to destroy this IFRAME, free memory, this also guarantees security (not by other domain frame JS access).

<script type= "Text/javascript" >

Iframe.contentWindow.document.write (");

Iframe.contentWindow.close ();

Document.body.removeChild (IFRAME);

</script>

In summary, the SRC attribute of the IFRAME is shifted from the domain to the local domain, and the cross-field data is transferred from the Window.name to the local domain by the IFRAME. This cleverly bypasses the browser's cross-domain access restrictions, but at the same time it is safe to operate.


5. Use HTML5 postMessage

One of the coolest new features in HTML5 is the cross-document messaging Messaging. 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 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. This can be the Contentwindow property of the IFrame in the page, the return value of the window.open, or the value taken 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 it's 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 source address of a message by Origin property

if (Event.origin = = ' http://a.com ') {

alert (event.data); Eject "I was there!"

alert (Event.source); A reference to the Window object in A.com, index.html

However, due to the same Origin policy, Event.source cannot access the window object here

}

}, False);

</script>

Reference article: Master HTML5 Programming Fifth-cross-document messaging mechanism, Https://developer.mozilla.org/en/dom/window.postmessage


6. Using Flash

This is the method seen from the IO component of YUI3, specifically visible http://developer.yahoo.com/yui/3/io/.

You can see more of the cross-domain proxy file specification in Adobe Developer connection: Ross-domain Policy, "File specifications," HTTP Headers blacklist.




About cross-domain can go to see these articles in the garden:

JavaScript cross-domain summary and workaround (http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html)

Cross-domain-knowledge (http://www.cnblogs.com/scottckt/archive/2011/11/12/2246531.html)

10 ways to share cross-domain resources (http://www.cnblogs.com/cat3/archive/2011/06/15/2081559.html)

HTML5 PostMessage ()

Http://www.cnblogs.com/dolphinX/p/3464056.html


JavaScript cross-domain Summary and solutions

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.