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 ';d ocument.body.appendChild (IFR); ifr.onload = function () {    var doc = Ifr.contentdocument | | ifr.contentWindow.document;    Manipulate b.html alert here    (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.readysta Te = = = ' 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 cannot modify parent.location.hash,//So to take advantage of an intermediary cnblogs domain under the proxy iframe var ifrproxy        = Document.createelement (' iframe ');        Ifrproxy.style.display = ' None ';    IFRPROXY.SRC = ' Http://a.com/test/cscript/cs3.html#somedata ';        //Note 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, they 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

Articles longer listed here are not easy to read, see the window.name implementation of cross-domain data transfer.

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 written as ' http://b.com/c/proxy.html ' effect  //if written ' Http://c.com ' will not 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) {        // Use the Origin property to determine the message source address        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                                  //But because of the same Origin policy, here Event.source cannot access the window object        }    , 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.

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.