Detailed JavaScript cross-domain summarization and solutions _javascript tips

Source: Internet
Author: User
Tags hash

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

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;
  Here manipulates b.html
  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.readysta Te = = "complete ') {
    //callback 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. Assume that the domain name a.com under the file cs1.html to and cnblogs.com domain name under the cs2.html to pass information, cs1.html first create a hidden iframe,iframe to create an automatic src point to the cnblogs.com domain name Cs2.html page, when the hash value can be used for parameter transfer. 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 processing operation
switch (location.hash) {case
  ' #paramdo ':
    callBack ();
    break;
  Case ' #paramset ':
    //do something
    ... break;

function CallBack () {
  try {
    parent.location.hash = ' somedata ';
  } catch (e) {
    //IE, The chrome security mechanism cannot modify the Parent.location.hash
    //So to take advantage of a middle 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 that the file is Document.body.appendChild (ifrproxy) under the "A.com" field
    ;
  }


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

There are three pages:

    1. A.com/app.html: Application page.
    2. A.com/proxy.html: Agent file, is generally an HTML file without any content, need and apply the page under the same domain.
    3. B.com/data.html: The page where the application page needs to get the data, can be called the data page.

The basic steps to achieve this are as follows:

1, in the Application page (a.com/app.html) to create an IFRAME, its SRC point 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 large to 32M or so
                   //data format can be customized, such as JSON, string
</script>

2, in the Application page (a.com/app.html) to monitor the onload incident in the IFRAME, this incident set this iframe to the SRC point to the local domain agent files (agent files and application pages in the same domain, so can communicate with each other). app.html part of the 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;  Read
      alert (data);  Eject ' I was there! '
    } else if (state = = 0) {state
      = 1;
      Iframe.contentWindow.location = "http://a.com/proxy.html";  Set Agent file
    } 
  };
  IFRAME.SRC = ' http://b.com/data.html ';
  if (iframe.attachevent) {
    iframe.attachevent (' onload ', LOADFN);
  } else {
    iframe.onload = LOADFN;
  }
  Document.body.appendChild (IFRAME);
</script>

3, the acquisition of data after the destruction of the IFRAME, freeing memory, this also guarantees the security (not by other domain frame JS access).

<script type= "Text/javascript" >
  iframe.contentWindow.document.write (');
  Iframe.contentWindow.close ();
  Document.body.removeChild (IFRAME);
</script>

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
                    is the
  same as//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) {
    / The Origin property is used to determine the message source address
    if (event.origin = = ' http://a.com ') {
      alert (event.data);  Pop "I was there!"
      alert (Event.source); References to a.com, index.html window objects
                 //But because of the homology policy, the Window object
    }, False is not accessible here Event.source
  ;

6, the use of flash
This is a way to see from the YUI3 IO component.
You can see more Cross-domain agent file specifications in Adobe Developer connection: ross-domain Policy file specifications, HTTP Headers blacklist.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.