JavaScript two cross-domain technology to introduce _javascript skills in a comprehensive way

Source: Internet
Author: User
Tags file url subdomain

This policy makes a significant restriction on the content of the page that JavaScript code can access, that is, JavaScript can only access content that is under the same domain as the document containing it.

JavaScript is a security policy that is especially important when it comes to multiple IFRAME or multiple window programming and AJAX programming. According to this strategy, the JavaScript code contained in the page under Baidu.com cannot access the content of the page under the google.com domain name, and even pages between different subdomains cannot be accessed through JavaScript code. The impact on Ajax is that Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains, such as pages under Abc.example.com, no AJAX requests to def.example.com, and so on.

However, when some of the more in-depth front-end programming, the inevitable need for cross-domain operations, this time "homology strategy" is too harsh. In this paper, we generalize some techniques that need to cross domain.

Here we discuss Cross-domain technology in two ways: first we discuss cross-domain technologies for different subdomains, and then we discuss cross-domain technologies in disparate domains.

(i) Cross-domain technologies for different subdomains.

We discuss two issues separately: the first is how to make JavaScript calls across different subdomains, and the second is how to submit AJAX requests to different subdomains.

To solve the first problem, assume that there are two different subdomains in the example.com domain: abc.example.com and def.example.com. Now suppose there is a page underneath the def.example.com that defines a JavaScript function:

Copy Code code as follows:
function Funcindef () {
.....
}

We want to call the above function on a page under Abc.example.com. Assuming we're going to discuss the abc.example.com below the page is embedded in the def.example.com below the page, so we might try to do the following in the IFRAME:

Copy Code code as follows:
Window.top.funcInDef ();

Well, we noticed that this call was banned by the "homology policy" mentioned earlier, and the JavaScript engine throws an exception directly.
To implement the above call, we can do so by modifying the domain property of the two pages. For example, we could add the following JavaScript code snippet to the top of the two pages above abc.example.com and def.example.com:
Copy Code code as follows:
Document.domain = "example.com";

In this way, two pages become the same domain, the previous call can be performed normally.

One thing to note here is that the Document.domain property of a page can only be set to a more top-level domain name (except for a first-level domain name), but it cannot be set to a subdomain that is deeper than the current domain name. For example, Abc.example.com's page can only set its domain to example.com, can not be set to sub.abc.example.com, of course, can not be set to a level of domain name COM.

The above example discusses the case where two pages belong to an IFRAME nesting relationship, and the principle is exactly the same when two pages open and open.

Here's a second question: How to submit an AJAX request to a different subdomain.
Typically, we create a XMLHttpRequest object with code similar to the following:

Copy Code code as follows:
Factories = [function () {
return new XMLHttpRequest ();
},
function () {
return new ActiveXObject ("Msxml2.xmlhttp");
},
function () {
return new ActiveXObject ("Microsoft.XMLHTTP");
}];
function Newrequest () {
for (var i = 0; I & lt; factories.length; i++) {
try {
var factory = Factories[i];
return Factory ();
catch (e) {}
}
return null;
}

ActiveXObject is referenced in the above code to be compatible with the IE6 series browser. Every time we call the Newrequest function, we get an Ajax object that we just created, and then we use this Ajax object to send the HTTP request. For example, the following code sends a GET request to abc.example.com:
Copy Code code as follows:

var request = Newrequest ();
Request.open ("Get", "http://abc.example.com");
Request.send (NULL);

Assuming the above code is contained in a page under a abc.example.com domain name, the GET request can be sent successfully without any problems. However, if you now want to send a request to def.example.com, a cross-domain problem occurs and the JavaScript engine throws an exception.
The solution is, Place a Cross-domain file under the def.example.com domain, assuming that it is called crossdomain.html, and then move the definition of the preceding newrequest function into the Cross-domain file, and finally, as before the Document.domain value, in the Crossdomain.h tml file and abc.example.com domain down with Ajax pages at the top, all plus:

Copy Code code as follows:
Document.domain = "example.com";


In order to use cross-domain files, we lowered the abc.example.com domain with an AJAX-enabled page to embed a hidden iframe that points to cross-domain files, for example:
Copy Code code as follows:
<iframe name= "Xd_iframe" style= "Display:none" src= "http://def.example.com/crossdomain.html" >
</iframe>


At this point, the page under the abc.example.com domain and the Cross-domain file crossdomain.html are all under the same domain (example.com), and we can invoke crossdomain.html in Newrequest in the page under abc.example.com domain Function:
Copy Code code as follows:
var request = window.frames["Xd_iframe"].newrequest ();

This gets the request object, and you can send HTTP requests to http://def.example.com.

(b) Cross-domain technology in a completely different domain.

If top-level domain names are not the same, such as example1.com and example2.com want to communicate through JavaScript in front of each other, the technology needed is more complex.

Before we talk about Cross-domain technologies in different domains, let's be clear that the following techniques apply equally to the previous cases across different subdomains, because cross domains are only one special case of cross-domain problems. Of course, using the right technology in the right circumstances can ensure better efficiency and greater stability.

In short, Cross-domain technologies can be grouped into the following categories, depending on different cross-domain requirements:
1. Jsonp cross-domain GET request
2. Cross-domain through IFRAME
3. Flash cross-Domain HTTP request
4, Window.postmessage
The following is a detailed description of the various technologies.
1. JSONP.
The method of submitting HTTP requests to different domains using the method of creating <script> nodes in a page is called JSONP, which solves the problem of submitting Ajax requests across domains. The working principle of JSONP is as follows:
Suppose you submit a GET request to http://example2.com/getinfo.php on the http://example1.com/index.php page, we can put the following JavaScript code in the http:// example1.com/index.php this page to implement:

Copy Code code as follows:
var elescript= document.createelement ("script");
Elescript.type = "Text/javascript";
ELESCRIPT.SRC = "http://example2.com/getinfo.php";
document.getElementsByTagName ("Head") [0].appendchild (Elescript);

When a GET request returns from http://example2.com/getinfo.php, a section of JavaScript code can be returned, which is automatically executed and can be used to invoke the http://example1.com/ Index.php a callback function in the page.

The advantage of JSONP is that it is not limited by the same homology policy as the AJAX request implemented by the XMLHttpRequest object; It is better compatible, can run in older browsers, and does not require XMLHttpRequest or ActiveX support , and the result can be returned by calling callback after the request has been completed.

The disadvantage of JSONP is that it only supports get requests and does not support other types of HTTP requests such as post, it only supports Cross-domain HTTP requests, and does not solve the problem of how to make JavaScript calls between two pages in different domains.

2. Cross-domain through IFRAME.

The IFRAME Cross-domain approach, which is more powerful than JSONP, can be used not only to complete HTTP requests across domains, but also to implement JavaScript calls across domains in the front-end. Therefore, the cross-domain problem of a completely different domain is usually solved by the way of IFRAME.

Similar to the way JSONP technology submits get requests to different domains by creating <script> nodes, we can also create points in the http://example1.com/index.php page to http:// The example2.com/getinfo.php IFRAME node submits a GET request across domains. However, the result returned by the request cannot be invoked back to the callback function in the http://example1.com/index.php page because it is affected by the "homology policy."

To solve this problem, we need to place a Cross-domain file under Example1.com, for example, the path is http://example1.com/crossdomain.html.

When http://example2.com/getinfo.php this request returns the result, it has roughly two choices.
The first option is that it can do a 302 jump in the IFRAME, jump to a Cross-domain file http://example1.com/crossdomain.html, and prefix the return result with a URL after the Cross-domain file URL, such as HTTP ://example1.com/crossdomain.html?result=<url-encoding-content>.

Another option is that it can embed an IFRAME in the returned page, point to a Cross-domain file, and then prefix the return result with a URL as a parameter behind the Cross-domain file URL.

In a Cross-domain file, contains a section of JavaScript code, which completes the function of extracting the result parameters from the URL, and then invoking the original http://example1.com/after certain processing. index.php a predefined callback function in the page, passing the result parameter to this function. http://example1.com/index.php pages and Cross-domain files are under the same domain, so this function call can be passed. The relationship between the IFRAME and the original http://example1.com/index.php page where the Cross-domain file resides, under the first selection, which is the parent window of the former, and under the second choice, the parent window of the former.

Based on the previous description, with Cross-domain files, we can implement JavaScript calls between different domains through an IFRAME. This invocation process can be completely unrelated to HTTP requests, for example, some sites can support dynamically adjusting the height of a third party iframe embedded in a page, which is actually detecting the height of a page in a third party IFRAME, This change is then communicated to the parent window through a function call across the domain.

Since IFRAME can be used to implement Cross-domain JavaScript calls, other types of HTTP requests such as POST requests across domains are not difficult. For example, we can call the target domain's JavaScript code across domains to submit an AJAX request (get/post/etc.) under the target domain, and then pass the returned results across the domain to the original domain.

The advantage of using an IFRAME across domains is that it is powerful, support a variety of browsers, can almost do anything cross-domain want to do; The disadvantage is to implement complex, to deal with a lot of browser compatibility issues, and the transmission of data should not be too large, too large may exceed the browser limit on the length of the URL, to consider the data for subsection transmission.

3. Implement cross domain HTTP request with flash

It is said that flash in the browser penetration rate of up to more than 90%.

Flash code and JavaScript code can be invoked between each other, and Flash's "security sandbox" mechanism is not the same as JavaScript security, so we can use Flash to implement Cross-domain HTTP requests (support Get/post, etc.).
For example, we use the browser to access the http://example1.com/index.php page, which refers to the http://example2.com/flash.swf Flash file in this page, and then in Flash code to HTTP ://example3.com/webservice.php send HTTP request.

Whether the request can be sent successfully depends on the placement of a crossdomain.xml under the root path of the example3.com and the configuration of the crossdomain.xml. Flash's "security sandbox" guarantees that the request can be truly successful only if the example3.com server does place the Crossdomain.xml file in the root path and the request to accept flash from example2.com is configured in this file. The following is an example of the contents of a Crossdomain.xml file:

Copy Code code as follows:

<?xml version= "1.0"?>
<cross-domain-policy>
<allow-access-from domain= "example2.com"/>
</cross-domain-policy>

4. Window.postmessage
Window.postmessage is a new feature supported by the next version of the HTML standard HTML5. With the rapid advances in Internet technology, the need for browser Cross-domain communication has become increasingly strong, and the HTML standard has finally taken into account cross-domain communication. But at present HTML5 is still only a draft.
Window.postmessage is a secure way to achieve direct cross-domain communication. But not all browsers are currently supported, and only Firefox 3, Safari 4, and IE8 can support this call.

Use it to send messages to other windows in the same way as you might call:

Copy Code code as follows:
Otherwindow.postmessage (message, targetorigin);

In the received window, you need to set up an event handler to receive the message sent over:
Copy Code code as follows:
Window.addeventlistener ("message", ReceiveMessage, false);
function ReceiveMessage (event) {
if (event.origin!== "http://example.org:8080") return;
}

The message contains three properties: Data, origin (which carries the real information of the field where the sending window is located) and source (representing the handle of the sending window).

Security considerations: Using Window.postmessage, you must use the origin and source properties of the message to verify the identity of the sender, or you can create an XSS vulnerability.

Window.postmessage is functionally as powerful as the Cross-domain functionality of the IFRAME, and is simple and efficient, but the downside is that it is currently being improved in terms of browser compatibility.

It is necessary to add to the original that, under Ie6,ie7, the opener of IE can be assignable to an object or function vulnerability, providing a supplementary scheme for the PostMessage scheme:
Main Page:

Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title>CrossDomain</title>
<body>
<iframe src= "http://sh-tanzhenlin/CrossDomain-child.html"
Frameborder= "0" visible= "false" height= "0" width= "0" id= "ifrchild" ></iframe>

<script type= "Text/javascript" >
var child = document.getElementById ("Ifrchild");
var openerobject = {
Funcinparent:function (ARG) {
Alert (ARG);
Alert (' executed by a function in parent page ');
}
}

if (!+ ' \v1 ' &&! ') 1 ' [0]) {//test browser is IE6 or IE7
Crack
Child.contentWindow.opener = Openerobject;
}
else{
PostMessage Showtime
}

function OnClick () {
Debugger
Openerobject.funciniframe (' Data from parent page ');
}
</script>
<input type= "button" value= "click Me" onclick= "onclick ()"/>
</body>

To embed a page under another domain with an iframe:

Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

<script type= "Text/javascript" >
onload = function () {
if (!+ ' \v1 ' &&! ') 1 ' [0]] {//test browser If is IE6 or IE7
Window.opener.funciniframe=function (ARG) {
Alert (ARG);
Alert (' executed by a function in IFrame ');
}
Window.opener.funcInParent (' data from IFrame ')
}
}
</script>
<body>
</body>

Note: The postmessage approach is being supported by a variety of new browsers at an unexpected rate and should be considered with emphasis.

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.