JavaScript cross-Domain access solution

Source: Internet
Author: User
Tags script tag domain server in domain to domain

JavaScript cross-domain access solutionCategory: WEB TIPS 2009-02-13 14:08 15882 people read reviews (5) favorite reports Javascriptiframeservletcallbackdomainfunction

JavaScript is limited to cross-domain access due to security considerations, but sometimes we want to be able to do some reasonable cross-domain access.
There are two types of situations:
One, based on the same parent domain to access the page between the child, see the following 3 domain domains: taobao.com, jipiao.taobao.com, promotion.taobao.com; they have the same parent domain taobao.com.
Second, based on the access between different parent domain pages, see the following 3 domain domains: taobao.com, baidu.com, sina.com.cn; they have different parent domains.

The scenarios for resolving cross-domain between them are:
Scenario 1: Server Proxy
Domain A's page JS needs to access the link under Domain B to obtain data, the scheme on the server side of domain A to establish a proxy program (possibly ASP, servlet, and any service-side program), Domain A's page JS directly invoke the proxy program under the domain, The proxy program is responsible for sending the request to the link under Domain B and obtaining the data, and then returning the data to the page JS using proxy.
After the access process is: Domain A JS--and domain A proxy--> Domain B under the link
Example:
The first step:
Domain a:http://jipiao.taobao.com/test.htm
JavaScript script on the page:

[JavaScript]View Plaincopy
  1. <mce:script type="Text/javascript" ><!--
  2. Var surl="http://Jipiao.taobao.com/proxy.do";//proxy address under this domain
  3. var callback =
  4. {
  5. Success: function (res) {alert (res.responsetext); },   
  6. Failure: function (res) {alert (' failure ');},
  7. argument:{}
  8. }
  9. YAHOO.util.Connect.asyncRequest (' GET ', sURL, callback, null);
  10. --></mce:script>

Step Two:
Complete the proxy program on domain A server (this is assumed to be a servlet), and the pseudo-code is as follows:
[Java]View Plaincopy
  1. Public class Proxy extends .... {
  2. .. Doget (...) {
  3. HttpClient client= ...;
  4. GetMethod get=New GetMethod ("www.baidu.com/xxxxx.do"); Access to domain B links
  5. int statusCode = Client.executemethod (get);
  6. if (statusCode! = HTTPSTATUS.SC_OK) {
  7. byte[] responsebody = Get.getresponsebody ();
  8. String res=new String (responsebody);
  9. Httpresponse.getwriter (). write (res); //Return data to domain a
  10. }
  11. }
  12. }

Scenario 2: through the script tag :
In the head of the Domain A page http://Jipiao.taobao.com/test.htm, write an empty script tag:

[XHTML]View Plaincopy
  1. <html>
  2. <head>
  3. <mce:script id="Remotescript" type="Text/javascript" src= "/><!--
  4. <head>
  5. <body>
  6. <script type="Text/javascript" >
  7. Var remotescript=document.getElementById ("Remotescript");
  8. remotescript.src="www.baidu.com/xxxxx.do";//link to domain B
  9. alert (remote.test);//JSON data returned using domain B
  10. Alert (f[0]);
  11. --></mce:script>
  12. </body>
  13. </html>

Note: This scenario requires that the data returned by Domain B must be in a valid JSON format or in the form of a JS file, for example, the data format returned by Domain B is as follows:
Var remote={test: ' Hello '};
Var f=[2,1];

Scenario 3: hide the iframe, share domain:
A hidden IFrame is written on the page http://jipiao.taobao.com/yyyy.htm the domain A page:

[XHTML]View Plaincopy
  1. <html>
  2. <head>
  3. <head>
  4. <body>
  5. <mce:script type="Text/javascript" ><!--
  6. document.domain="taobao.com";
  7. Var remotehtml=document.getElementById ("remotehtml");
  8. remotehtml.src="promotion.taobao.com/xxxx.htm";//access the link to domain B here
  9. var document=remotehtml.contentdocument;//You can use document to manipulate the data in the page xxx.htm in domain B.
  10. --></mce:script>
  11. <iframe id="remotehtml" src= " style=" Diapay:none " mce_style=" Diapay: None "/>
  12. </body>
  13. </html>

Note: This http://promotion.taobao.com/xxxx.htm page also needs to be set document.domain= "Taobao.com", this method can be effective.
The method of this iframe is not suitable for cross-domain between different parent domains, because setting Document.domain can only be set to its own parent domain, not to other domains, for example: Jiapiao.taobao.com can only be set document.domain= "Taobao.com", but not document.domain= "baidu.com";

Each of the three scenarios listed here has advantages and disadvantages :
The advantage of the proxy scheme is that it can be applied to almost all cross-domain access, and only needs to be developed in one domain, and the other domain can provide data in any type of format. The disadvantage is that this scheme passes the intermediate proxy, so the delay may be slightly larger, and will aggravate the load on the domain server, and the development effort is slightly larger.
The script tag scheme can be said to be very simple, without a few lines of code to get it done, but it on the return of the data format requirements are a bit strict, can only be JSON format data, if it is other formats of data, then this method is powerless.
Hiding the IFRAME is also simple, it can handle any returned data format, but it only applies to cross-domain requests under the same parent domain, and requires other domains to be developed in conjunction with the need to set document.domain.

See the original post: http://blog.csdn.net/lovingprince/archive/2008/09/20/2954675.aspx

For the meaning of JS cross-domain access, I would like to add a few points:

    1. Cross-domain access, in a nutshell, is the JavaScript code of the A site that attempts to access the B site, including submissions and access to content , for example, to execute a JS object from a page in the site A, Or if you want to use JS to parse the DOM elements of a page in site A on the website of site A, the scenario where this cross-domain access problem occurs is usually a page embedded in a different domain in an iframe, or an AJAX request sent to a different domain;
    2. For security reasons, cross-domain access is forbidden by the major browsers, but the browser does not prohibit reference to other fields in the page JS files, and can freely execute the introduced JS file function;
    3. Whether cross-domain judgment rule is to compare three: domain name, protocol, Port ; if one of the three is not the same, there will be cross-domain problem; we often say that cross-domain issues generally refer to different domain names because this scenario is the most likely to occur and there are ways to solve it. , such as the above mentioned in the taobao.com domain two domain name cross-domain problem;
    4. For the main domain is not the same, or the protocol is different (such as HTTPS and HTTP) cross-domain issues (such as the *.taobao.com domain to access the contents of the *.baidu.com domain), want to solve from the web side is completely impossible, can only be resolved through the service-side proxy scheme;
    5. Common page constraints between different domains DOM elements include:
      Window.location can be set, but cannot be read. Other location properties and methods are forbidden;
      Document.href can be set, but cannot be read. Other document properties and methods are forbidden to access;
      <iframe> src can be set, but cannot be read;

JavaScript cross-domain access solution

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.