JavaScript cross-origin summary and Solutions

Source: Internet
Author: User

What is cross-Origin
For security reasons, JavaScript does not allow cross-origin calls to objects on other pages. However, security restrictions also bring a lot of trouble to inject iframe or ajax applications. Here we will simply sort out the cross-origin problems:

First of all, what is cross-origin is simply because of restrictions on the JavaScript same-origin policy. js under the.com domain name cannot operate on B .com or the objects under the c.a.com domain name. For more details, see the following table:

URL indicates whether communication is allowed
Http://www.a.com/a.js
Http://www.a.com/ B .js allowed under the same domain name
Http://www.a.com/lab/a.js
Different folders under the same domain name allow http://www.a.com/script/ B .js
Http://www.a.com: 8000/a. js
Http://www.a.com/ B .js with the same domain name, different ports not allowed
Http://www.a.com/a.js
Https://www.a.com/ B .js for the same domain name, different protocols are not allowed
Http://www.a.com/a.js
Http: // 70.32.92.74/B. js domain name and the corresponding ip address of the domain name are not allowed
Http://www.a.com/a.js
The primary domain of the http://script.a.com/ B .js is the same and different subdomains are not allowed
Http://www.a.com/a.js
The same domain name of the http://a.com/ B .js, different second-level domain names (same as above) are not allowed (cookie in this case is not allowed to access)
Http://www.cnblogs.com/a.js
Different http://www.a.com/ B .js domain names are not allowed
Pay special attention to the following two points:
First, if the cross-domain problem caused by protocols and ports is "front-end,
Second, on cross-origin issues, the domain is identified only by the "URL Header" instead of trying to determine whether the same ip address corresponds to two domain or two domain names on the same ip address.
"URL Header" refers to window. location. protocol + window. location. host. It can also be understood as "Domains, protocols and ports must match ".
Next, let's briefly summarize the general cross-origin processing methods at the "front-end". The background proxy scheme involves background configuration, which is not described here. If you are interested, please refer to yahoo's article: javaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest CILS

1. document. domain + iframe settings
For examples with the same primary domain and different subdomains, you can set document. domain. The specific method is to create an iframe through the.html file after creating = 'a.com', to control the contentDocument of iframe, so that the two js files can "interact. Of course, this method can only solve the problem where the primary domain is the same but the second-level domain name is different. If you set the domian of script.a.com to alibaba.com in a whimsical manner, it will obviously report an error! The Code is as follows:

A.html on 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.content##doc ument;
// Operate B .html here
Alert (doc. getElementsByTagName ("h1") [0]. childNodes [0]. nodeValue );
};
B .html on script.a.com

Document. domain = 'a. com ';
This method applies to communication between any pages in {www.kuqin.com, kuqin.com, script.kuqin.com, and css.kuqin.com.

Note: The domain of a page is equal to window. location. hostname by default. The primary domain name is a domain name without www, such as a.com. The primary domain name is usually prefixed with a second-level domain name or multi-level domain name. For example, www.a.com is actually a second-level 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 a security vulnerability.
2. If multiple iframe is introduced to a page, you must set the same domain to operate all iframe operations.
2. dynamically create scripts
Although cross-origin access is disabled by default, the browser does not prohibit reference JS files of other domains in the page, and can freely execute the functions (including cookie and Dom operations) in the introduced JS files ). Based on this, you can easily create a script node to implement full cross-origin communication. For specific practices, refer to the YUI Get Utility

It is quite interesting to judge whether the script node is loaded: ie can only use the readystatechange attribute of the script, and other browsers are the load events of the script. The following describes how to determine whether a script has been loaded.

Js. onload = js. onreadystatechange = function (){
If (! This. readyState | this. readyState = 'loaded' | this. readyState = 'complete '){
// Callback is executed here
Js. onload = js. onreadystatechange = null;
}
};
3. Use iframe and location. hash
This method is relatively difficult, but it can solve the problem of step replacement in the case of full cross-origin. The principle is to use location. hash to transmit values. '# Helloworld' in url: http://a.com # helloword is location. changing the hash does not cause page refreshing. Therefore, you can use the hash value for data transmission. Of course, the data capacity is limited. In this case, the hash value can be used for parameter transfer. Cs2.htmlafter the request is received, the modified cs1.html hash value will be passed for data transmission (because the two pages are not in the same domain, IE and Chrome cannot modify the parent. location. hash Value, so you need to use a proxy iframe under the.com domain name; Firefox can be modified ). Add a timer to cs1.html at the same time to judge whether the location. hash Value has changed over a period of time. If there is any change, obtain the hash value. The Code is as follows:

First, the 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 cnblogs.comdomain 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 ){
// The Security Mechanism of ie and chrome cannot be modified by parent. location. hash,
// Use the proxy iframe in an intermediate 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 in the "a.com" Domain
Document. body. appendChild (ifrproxy );
}
}
A.comdomain name cs3.html

// Because parent. parent belongs to the same domain, you can change its location. hash Value.
Parent. parent. location. hash = self. location. hash. substring (1 );
Of course, this operation also has many disadvantages, such as direct data exposure to URLs, limited data capacity and types ......

4. Cross-Origin data transmission implemented by window. name
This article is not easy to read. For more information, see cross-domain data transmission implemented by window. name.

5. Use HTML5 postMessage
One of the coolest new features in HTML5 is Cross-Document message transmission. The next-generation browsers will support this function: Chrome 2.0 +, Internet Explorer 8.0 +, Firefox 3.0 +, Opera 9.6 +, and Safari 4.0 +. Facebook has used this function to support real-time web-based message transmission using postMessage.

OtherWindow. postMessage (message, targetOrigin );
OtherWindow: Reference to the window on the receiving information page. It can be the contentWindow attribute of iframe on the page, the return value of window. open, and the value obtained from window. frames through name or subscript.
Message: The data to be sent, of the string type.
TargetOrigin: used to restrict otherWindow. "*" indicates no restriction.
A.com/index.html code:

<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 '; // The result is the same if 'HTTP: // B .com/c/proxy.html' is written.
// If it is written as 'HTTP: // c.com ', no postMessage will be executed.
Ifr. contentWindow. postMessage ('I was there! ', TargetOrigin );
};
</Script>
B .com/index.html code:

<Script type = "text/javascript">
Window. addEventListener ('message', function (event ){
// Determine the message source address through the origin attribute
If (event. origin = 'HTTP: // a.com '){
Alert (event. data); // The "I was there! "
Alert (event. source); // reference the window object in a.com;index.html
// However, due to the same-origin policy, event. source cannot access the window object.
}
}, False );
</Script>
Chapter 5 of "proficient in HTML5 programming" -- Cross-document message mechanism, https://developer.mozilla.org/en/dom/window.postmessage

6. use flash
This is the method we can see from YUI3's IO components. For details, see http://developer.yahoo.com/yui/3/io /.
You can see more cross-origin proxy File Specifications in Adobe Developer Connection: ross-Domain Policy File Specifications, HTTP Headers Blacklist
Author: watye

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.