JavaScript cross-domain summarization and solutions

Source: Internet
Author: User
Tags object hash header html page new features window domain domain name

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:

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, which can also be understood as "Domains, protocols and Ports 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 XMLHttpRequest Calls "

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 of http://www.a.com/a.html and http://script.a.com/b.html respectively; 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 same and two domain name different situation, if you whimsical to the script.a.com Domian set for Alibaba.com that is obviously will be the error! The code is as follows:

The a.html on the www.a.com

 
  
  
  1. Document.domain = "A.com";
  2. var IFR = document.createelement ("iframe");
  3. IFR.SRC = "http://script.a.com/b.html";
  4. Ifr.style.display = "None";
  5. Document.body.appendChild (IFR);
  6. Ifr.onload = function () {
  7. var doc = Ifr.contentdocument ifr.contentWindow.document;
  8. To manipulate b.html here.
  9. Alert (Doc.getelementsbytagname ("H1") [0].childnodes[0].nodevalue);
  10. };

The b.html on the script.a.com

 
  
  
  1. 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 specific procedure may refer to Yui's get Utility

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.

 
  
  
  1. Js.onload = Js.onreadystatechange = function () {
  2. if (!this.readystate this.readystate = = "loaded" this.readystate = = = "complete") {
  3. Callback is here to perform
  4. Js.onload = Js.onreadystatechange = null;
  5. }
  6. };

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. If the domain name a.com under the file cs1.html to and cnblogs.com domain name under the cs2.html transmission information, cs1.html first create a hidden iframe,iframe of SRC to point to the cnblogs.com domain name cs2.html page, then H The ash value can be used for parameter passing. 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 the use of the a.com domain name under a proxy iframe; Firefox can be modified). 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:

 
 
  1. function Startrequest () {
  2. var IFR = document.createelement ("iframe");
  3. Ifr.style.display = "None";
  4. IFR.SRC = "Http://www.cnblogs.com/lab/cscript/cs2.html#paramdo";
  5. Document.body.appendChild (IFR);
  6. }
  7. function Checkhash () {
  8. try {
  9. var data = Location.hash? Location.hash.substring (1): "";
  10. if (Console.log) {
  11. Console.log ("Now the data is" +data);
  12. }
  13. catch (e) {};
  14. }
  15. SetInterval (Checkhash, 2000);

Cs2.html under the cnblogs.com domain name:

 
 
  1. Simulate a simple parameter-handling operation
  2. Switch (Location.hash) {
  3. Case "#paramdo":
  4. CallBack ();
  5. Break
  6. Case "#paramset":
  7. Do something ...
  8. Break
  9. }
  10. function CallBack () {
  11. try {
  12. Parent.location.hash = "Somedata";
  13. catch (e) {
  14. The security mechanism of IE and chrome cannot modify Parent.location.hash,
  15. So to use a proxy iframe in the middle of the cnblogs domain
  16. var ifrproxy = document.createelement ("iframe");
  17. Ifrproxy.style.display = "None";
  18. IFRPROXY.SRC = "Http://a.com/test/cscript/cs3.html#somedata"; Note that the file is under the "a.com" field
  19. Document.body.appendChild (Ifrproxy);
  20. }
  21. }

A.com under the domain cs3.html

 
  
  
  1. Because Parent.parent and itself belong to the same domain, you can change the value of its Location.hash
  2. 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

The article is longer listed here is not easy to read, please see Window.name implementation of cross-domain data transfer.

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: Chrome 2.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:

 
 
  1. <iframe id= "IFR" src= "b.com/index.html" ></iframe>
  2. <script type= "Text/javascript" >
  3. Window.onload = function () {
  4. var IFR = document.getElementById ("IFR");
  5. var targetorigin = "http://b.com"; If written "http://b.com/c/proxy.html" effect
  6. If you write "http://c.com", you won't execute postmessage.
  7. Ifr.contentWindow.postMessage ("I was there!", targetorigin);
  8. };
  9. </script>

Code in b.com/index.html:

 
 
  1. <script type= "Text/javascript" >
  2. Window.addeventlistener ("Message", function (event) {
  3. To determine the message source address by Origin property
  4. if (Event.origin = = "Http://a.com") {
  5. alert (event.data); Pop "I was there!"
  6. alert (Event.source); References to Window objects in A.com, index.html
  7. But because of the homology policy, the window object is not accessible here Event.source
  8. }
  9. }, False);
  10. </script>

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

"Edit Recommendation"

    1. Developing mobile applications using JavaScript
    2. Implementing tabular data Management with JavaScript
    3. JavaScript version of several common sorting algorithms to share
    4. JavaScript objects and the built-in objects of the inheritance tutorial
    5. JavaScript memory recovery mechanism in depth interpretation
"Responsible editor: Chen Yu new TEL: (010) 68476606"


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.