Js cross-origin problem summary

Source: Internet
Author: User

This article comes from:Http://www.kuqin.com/webpagedesign/20090422/47458.html

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. If you remember correctly, someone mentioned this item every time on the D2 Forum of the previous three sessions. 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 Description Allow communication?
Http://www.kuqin.com/lab/a.js
Http://www.kuqin.com/script/ B .js
Different folders under the same domain name Allow
Http://www.kuqin.com/a.js
Http://www.kuqin.com/ B .js
Under the same domain name Allow
Http://www.kuqin.com: 8000/a. js
Http://www.kuqin.com/ B .js
Different ports for the same domain name Not Allowed
Http://www.kuqin.com/a.js
Https://www.kuqin.com/ B .js
Different protocols for the same domain name Not Allowed
Http://www.kuqin.com/a.js
Http: // 70.32.92.74/B. js
Corresponding ip addresses of domain names and domain names Not Allowed
Http://www.kuqin.com/a.js
Http://script.kuqin.com/ B .js
The primary domain is the same and the subdomain is different. Not Allowed
Http://www.ithao123.com/a.js
Http://www.kuqin.com/ B .js
Different domain names 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.

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. You can create an iframe in the a.html file after creating = 'kuqin.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.kuqin.com to alibaba.com in a whimsical manner, it will obviously report an error! The Code is as follows:
A.html on www.kuqin.com

123456789
        document.domain = 'kuqin.com';var ifr = document.createElement('iframe');ifr.src = 'http://script.kuqin.com/b.html';ifr.style.display = 'none';document.body.appendChild(ifr);ifr.onload = function(){var x = ifr.contentDocument;alert(x.getElementsByTagName("h1")[0].childNodes[0].nodeValue);}

B .html on script.kuqin.com

1
 document.domain = 'kuqin.com';

2. dynamically create scripts
Although the browser disables cross-origin access by default, it does not prohibit reference JS files of other domains in the page, and can freely execute the function in the introduced JS file. 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, Safari 3. x and above support the script load event, while firefox and oprea should be solved through onload. In addition, this method can only transmit js data, which is not very convenient. The following describes how to determine whether a script has been loaded.

123456789101112131415161718192021222324252627282930313233
...... // Ie supports the readystatechange attribute of the script // IE supports the readystatechange event for script and css nodesif (ua. ie) {n. onreadystatechange = function () {var rs = this. readyState; if ("loaded" = rs | "complete" = rs) {n. onreadystatechange = null; f (id, url );}};...... /// Safari 3.x supports the load event for script nodes (DOM2 )...... N. addEventListener ("load", function () {f (id, url );});...... // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. opera, but not FF, supports the onload event for link // nodes .} else {n. onload = function () {f (id, url );};}

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://kuqin.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. After cs2.htmlresponds to the request, the hash value of cs1.html will be modified to pass data. (Because ie cannot modify the value of parent. location. hash, you need to use a proxy iframe under the kuqin.com domain name ). 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 kuqin.com:

12345678910111213141516
function startRequest(){var ifr = document.createElement('iframe');ifr.style.display = 'none';ifr.src = 'http://www.ithao123.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 ithao123.comdomain Name:

1234567891011121314151617181920212223
(Function () {// 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';} the security mechanism of catch (e) {// ie cannot be modified. location. hash, so we need to use a proxy iframe var ifrproxy = document. createElement ('iframe'); ifrproxy. style. display = 'none'; ifrproxy. src = 'HTTP: // kuqin.com/test/cscript/cs3.html?somedata'; document. body. appendChild (ifrproxy );}}})();

Cs3.html

12
// Because of parent. parent and itself belong to the same domain, so you can change the location in ie. hash Value parent. parent. location. hash = self. location. hash. substring (1 );

For an instance, click hash to implement full cross-Origin
Of course, this operation also has many disadvantages, such as direct data exposure to URLs, limited data capacity and types ......

4. Use flash
This is the way to see from YUI3 IO components, specific visibility: http://developer.yahoo.com/yui/3/io/
Flash is not very clear about this solution. You may think about it slowly. You can see more cross-origin proxy file specifications in Adobe Developer Connection:
Ross-Domain Policy File Specifications.
HTTP Headers Blacklist.

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.