Javascript-cross-Domain implementation method summary __java

Source: Internet
Author: User
A summary of the implementation methods of JavaScript Cross-domain value-taking

Recently in learning JS Cross-domain, found two a good blog, share. 1 JavaScript cross-domain summarization and solutions

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, or "domains,protocols and ports must 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 Xmlhttprequestcalls "

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 as 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 () {

Vardoc = 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 concrete procedure may refer to Yui's getutility

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

There are three pages:

A.com/app.html: Application page.

A.com/proxy.html: Agent file, is generally an HTML file without any content, need and apply the page under the same domain.

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:

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:

<scripttype= "Text/javascript" >

Window.name = ' I was there! '; Here is the data to be transmitted, the size of the general 2m,ie and Firefox can be large to 32M or so

Data formats can be customized, such as JSON, string

</script>

In the Application page (a.com/app.html) to monitor the onload event of the IFRAME, this event set this iframe 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:

<scripttype= "Text/javascript" >

var state = 0,

iframe = document.createelement (' iframe '),

LOADFN = function () {

if (state = = 1) {

var data = Iframe.contentWindow.name; Reading data

alert (data); Pop ' I wasthere! '

else if (state = = 0) {

state = 1;

Iframe.contentWindow.location = "http://a.com/proxy.html"; Proxy file set by

}

};

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

if (iframe.attachevent) {

Iframe.attachevent (' onload ', LOADFN);

}else {

Iframe.onload = LOADFN;

}

Document.body.appendChild (IFRAME);

</script>

After the data is retrieved, the IFRAME is destroyed and the memory is freed, which is guaranteed to be secure (not accessed by the other domain frame JS).

<scripttype= "Text/javascript" >

Iframe.contentWindow.document.write (");

Iframe.contentWindow.close ();

Document.body.removeChild (IFRAME);

</script>

summed up namely: the SRC attribute of the IFRAME from Outland to the local domain, Cross-domain data that is from the window.name of the IFRAME from Outland to the local domain. This cleverly bypasses the browser's Cross-domain access restrictions, but it is also a safe operation.

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

<scripttype= "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:

<scripttype= "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-up "I wasthere!"

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.

Original: http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html


2 Elegant and wonderful JavaScript cross-domain problem solving solution

In this year's Baidu salon sharing session, Huangfanglong's "Art of Web Data interaction" mentions a very elegant and wonderful solution. Words not much said, directly on the solution schematic diagram:


The issues to be addressed in the figure are described below:

Under the aaa.com domain name of the index.htm page embedded in the bbb.com domain name under a page index.htm, under normal conditions within the IFRAME index.htm page is unable to access the parent page index.htm any DOM object or JS function, because cross-domain, but we often Also need to do some parameters to return things to do. The above method of implementation is a good solution to this problem;

The key elegance of the solution is that although the browser will prevent JS from accessing the objects on the page across domains, there is no limit to the hierarchical reference of the IFRAME, that is, the parent is still available; The solution is to use 2 layers of embedded IFRAME, The use of the second level of IFRAME in the page and parent.parent of the page is the relationship with the domain name, so as to avoid cross-domain problems to achieve the transfer of data between two pages, is essentially the use of parent.parent to achieve the parent page JS callback.

Let me give you a practical case:

Function Description:

A domain name under the page index.htm embedded an iframe page, the IFRAME refers to the B domain name sub-index.htm page, but in order to avoid appearing in the index.htm page scroll bar, we need to know clearly sub- Index.htm the height and width of the page, but sub-index.htm page content is not controllable, may vary depending on the user page size will be different; the problem is how to pass the height and width of the sub-index.htm page to the index.htm page.

Specific solution:

1. Declare a JS function process (height,width) in the Index.htm page, and use it to set the height and width of the iframe within the page;

2, in the Sub-index.htm page again embedded a hidden iframe,iframe of Src point a domain name under the page ex.htm?height=xx&width=yy, the page does not have any content, Only used to pass sub-index.htm page after loading the width and height of these two data, the page JS get request in the parameters directly after the call parent.parent.process (height, width); Finish setting the width and height of the parent page;

Look at this sequence diagram as follows:


Original: Http://www.csdn123.com/html/exception/itweb.php?url= ahr0cdovl3d3dy5tewv4y2vwdglvbi5jbi9qyxzhc2nyaxb0lze1njq5mjuuahrtba==

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.