English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
What is cross-domain
For security reasons, JavaScript does not allow cross-domain calls to objects in other pages. However, at the same time, this also brings a lot of trouble to injecting iframes or AJAX applications. Here, some issues related to cross-domain are simply summarized:
What is cross-domain? Simply put, it is because of the restriction of JavaScript's same-origin policy, the JavaScript under the a.com domain cannot operate the objects under the b.com or c.a.com domain. More detailed explanations can be found 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 | Allowed |
http://www.a.com/lab/a.js http://www.a.com/script/b.js |
Different folders under the same domain | Allowed |
http://www.a.com:8000/a.js http://www.a.com/b.js |
Same domain, different ports | is not allowed |
http://www.a.com/a.js https://www.a.com/b.js |
Same domain, different protocols | is not allowed |
http://www.a.com/a.js http://70.32.92.74/b.js |
Domain name and corresponding IP address | is not allowed |
http://www.a.com/a.js http://script.a.com/b.js |
Main domain is the same, subdomain is different | is not allowed |
http://www.a.com/a.js http://a.com/b.js |
Same domain, different second-level domains (as above) | Disallowed (not allowed to access in this case either, such as cookies) |
http://www.cnblogs.com/a.js http://www.a.com/b.js |
different domains | is not allowed |
Pay special attention to two points:
First, if the cross-domain problem is caused by protocols and ports, the "front-end" is powerless.
Second: In cross-domain issues, the domain is only identified through the "URL header" and will not attempt to judge whether the same ip address corresponds to two domains or whether two domains are on the same ip.
"URL header" refers to window.location.protocol +window.location.host, can also be understood as "Domains, protocols, and ports must match".
Next, let's simply summarize the general methods for handling cross-domain issues on the "front-end", the backend proxy scheme involves backend configuration, which will not be elaborated here.
1, document.domain+the iframe settings
For the case where the main domain is the same but the subdomain is different, the problem can be solved by setting document.domain. Specifically, it can be set inhttp://www.a.com/a.htmlandhttp://script.a.com/b.htmlAdd document.domain = 'a.com' to both files respectively, and then create an iframe in the a.html file to control the contentDocument of the iframe, so that the two js files can "interact" with each other. Of course, this method can only solve the problem of the same main domain but different second-level domains. If you whimsically set the domain of script.a.com to alibaba.com, it will obviously result in an error! The code is as follows:
www.a.comon a.html
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, manipulate b.html alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue); };
b.html on script.a.com
document.domain = 'a.com';
This method is applicable to any page in {www.kuqin.com, kuqin.com, script.kuqin.com, css.kuqin.com} for intercommunication.
Note: The default domain of a page is equal to window.location.hostname. The main domain is the domain without www, such as a.com, and the domain with a prefix in front of it is usually a second-level domain or multi-level domain, such aswww.a.comIt is actually a second-level domain. The domain can only be set to the main domain, and it cannot be set to c.a.com in b.a.com.
Question:
1Security, when one site (b.a.com) is attacked, another site (c.a.com) may cause a security vulnerability.
2If multiple iframes are introduced in a page, in order to be able to operate all iframes, it is necessary to set the same domain for all of them.
2Dynamically creating script
Although browsers by default prohibit cross-domain access, they do not prohibit referencing JS files from other domains in the page, and can freely execute functions in the JS files introduced (including operations on cookies, Dom, etc.). Based on this, it is convenient to implement completely cross-domain communication through the creation of script nodes. The specific method can refer to YUI's Get Utility
It's quite interesting to judge whether the script node is loaded: IE can only go through the script's readystatechange attribute, while other browsers are the script's load event. Here are some methods to judge whether the script is loaded.
js.onload = js.onreadystatechange = function() { if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') { // The callback is executed here js.onload = js.onreadystatechange = null; } };
3Using iframe and location.hash
This method is a bit roundabout, but it can solve the problem of script substitution in completely cross-domain situations. The principle is to use location.hash for value transmission. In the url: http://a.com#hellowordThe '#'helloworld' in it is the location.hash. Changing the hash does not cause the page to refresh, so hash values can be used for data transmission. Of course, the data capacity is limited. Suppose the file cs under the domain a.com1.html needs to be in sync with the cs under the cnblogs.com domain2.html passes information, cs1.html first creates an automatically generated hidden iframe, the src of which points to the cs under the cnblogs.com domain2.html page, and the hash value at this time can be used as a parameter for passing. cs2.html responds to the request, modify cs1.html hash value to pass data (since the two pages are not in the same domain, IE and Chrome do not allow the value of parent.location.hash to be modified, so we need to rely on a proxy iframe under the a.com domain; Firefox can modify it). At the same time, after cs1.html file, to judge whether the value of location.hash changes from time to time. If there is a change, then get the hash value. The code is as follows:
Firstly, add a timer to the cs1.html file:
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 '+catch(e) {}; } } } setInterval(checkHash, 2000);
cs under the cnblogs.com domain2.html:
//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 ie and chrome cannot modify parent.location.hash // So it is necessary to use a proxy iframe under the cnblogs domain var ifrproxy = document.createElement('iframe'); ifrproxy.style.display = 'none'; ifrproxy.src = 'http://a.com/test/cscript/cs3.html#somedata'; // Note that this file is under the domain "a.com" document.body.appendChild(ifrproxy); } }
a.com under the domain cs3.html
//Because parent.parent and itself belong to the same domain, so you can change the value of its location.hash parent.parent.location.hash = self.location.hash.substring(1);
Of course, this method also has many disadvantages, such as data being directly exposed in the url, limited data capacity and type, etc. ...
4Cross-domain data transmission using window.name
There are three pages:
The basic steps to implement it are as follows:
1In the application page (a.com/In app.html), create an iframe and set its src to the data page (b.com/data.html).
The data page will attach the data to this iframe's window.name, and the code of data.html is as follows:
<script type="text/javascript"> window.name = 'I was there!'; // This is the data to be transmitted, the size is generally2M, IE and firefox can be roughly32M左右 // The data format can be customized, such as json, string </script>
2In the application page (a.com/Listen to the onload event of the iframe in app.html, and set this iframe's src to the local domain's proxy file (the proxy file and the application page are in the same domain, so they can communicate with each other). Part of the code in app.html 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 data alert(data); //Pop up 'I was there!�� else if (state === 0) { state = 1; iframe.contentWindow.location = "http://a.com/proxy.html"; // the proxy file set } }; iframe.src = 'http://b.com/data.html'; if (iframe.attachEvent) { iframe.attachEvent('onload', loadfn); } else { iframe.onload = loadfn; } document.body.appendChild(iframe); </script>
3, destroy this iframe after getting the data to free up memory; this also ensures security (not accessed by other domain frames js).
<script type="text/javascript"> iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe); </script>
5, using HTML5 postMessage
HTML5One of the coolest new features is Cross Document Messaging. The next generation of 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, using postMessage to support real-time messaging based on the web.
otherWindow.postMessage(message, targetOrigin);
otherWindow: Reference to the window of the page receiving the information. It can be the contentWindow property of an iframe in the page; the return value of window.open; or the value obtained from window.frames by name or index.
message: The data to be sent, string type.
targetOrigin: Used to limit otherWindow, "*" means 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'; // proxy.html' will have the same effect//b.com/c/proxy.html'效果一样 // proxy.html' will have the same effect//If written as 'http: 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); // Pop up "I was there!" alert(event.source); // reference to the window object in a.com, index.html // But due to the same-origin policy, event.source cannot access the window object here } }, false);
6and using flash
This is from YUI3methods seen in the IO component
You can see more cross-domain proxy file specifications on Adobe Developer Connection: ross-Domain Policy File Specifications, HTTP Headers Blacklist.
That's all for this article. Hope it helps everyone's learning and also hope everyone will support the Yelling Tutorial more.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content that is suspected.)