Huang Cong: Javascript cross-origin Access Solution

Source: Internet
Author: User
Tags in domain to domain

Due to security considerations, Javascript is restricted by cross-origin access capabilities. But sometimes we want to do some reasonable cross-origin access things, what should we do?
There are two types of situations:
1. Access between subdomains based on the same parent domain. For details, see taobao.com, jipiao.taobao.com, and promotion.taobao.com. They have the same parent domain taobao.com.
2. Access between pages based on different parent domains. See the following three domain domains: taobao.com, baidu.com, and sina.com.cn. They have different parent domains.

The cross-origin solutions are as follows:
Solution 1:Server Proxy
Domain
Page JS of A needs to access the Link under Domain B to obtain data. This solution creates A Proxy Program (possibly any server program such as ASP and servlet) on the server side of Domain ), domain A Page
Face. JS directly calls the Proxy program in the current domain. The proxy program is responsible for sending the request to the link under Domain B and obtaining the data. Finally, the data is returned to the page. JS is used.
The access process is: JS under Domain A --> Proxy under Domain A --> Link under Domain B
Example:
Step 1:
Domain A: http://Jipiao.taobao.com/test.htm
Javascript script on the page:

[Javascript: firstline [1]View plaincopy
  1. <Mce: script type = "text/javascript"> <! --
  2. Var sUrl = "http://Jipiao.taobao.com/proxy.do"; // The proxy address in 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 2:
Complete the Proxy program on the server side of Domain A (A servlet is assumed here). The pseudo code is as follows:[Java: firstline [1]View plaincopy

  1. Public class Proxy extends ....... {
  2. ... DoGet (........) {
  3. HttpClient client = ......;
  4. GetMethod get = new GetMethod ("www.baidu.com/xxxxx.do"); // access the link of Domain B
  5. Int statusCode = client.exe cuteMethod (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
  10. }
  11. }
  12. }

Solution 2:Using Script labels:
Write an empty Script tag in the head of the domain A page http://Jipiao.taobao.com/test.htm:

[Xhtml: firstline [1]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 of Domain B
  9. Alert (remote. test); // use JSON data returned by Domain B
  10. Alert (f [0]);
  11. // --> </Mce: script>
  12. </Body>
  13. </Html>

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

Solution 3:Hide iframe and shared domain:
That is, write A hidden iframe on the page of the http://jipiao.taobao.com/yyyy.htm of the domain A page:

[Xhtml: firstline [1]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 of Domain B
  9. Var document = remoteHtml. ContentDocument; // you can use documentto operate the xxx.htm data on the page in Domain B.
  10. // --> </Mce: script>
  11. <Iframe id = "remoteHtml" src = "" style = "diapay: none" mce_style = "diapay: none"/>
  12. </Body>
  13. </Html>

Note: here the http://promotion.taobao.com/xxxx.htm page also needs to set document. domain = "taobao.com", this method can work.
Of
Therefore, this iframe method is not suitable for cross-domain communication between different parent domains, because you can only set document. domain to your parent domain rather than other domains. For example
For example, jiapiao.taobao.com can only set document. domain = "taobao.com", not
Document. domain = "baidu.com ";

The three solutions listed hereAdvantages and disadvantages:
The advantage of the Proxy solution is that it can be used for almost all cross-origin access, and only needs to be developed in one domain, and the other domain can provide data of any type. The disadvantage is that this scheme passes through the intermediate Proxy, so the latency may be slightly higher, and the load on the local server will be increased, and the Development workload will be slightly larger.
The Script tag solution is very simple and can be done without a few lines of code. However, it has strict requirements on the format of returned data and can only be Json data, for data in other formats, this method is useless.
Hiding iframe is also very simple. It can process any returned data format, but it is only applicable to cross-origin requests with the same parent domain, and requires that other domains be developed in combination, you need to set document. domain.

Original post for details: http://blog.csdn.net/lovingprince/archive/2008/09/20/2954675.aspx

 

 

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

  1. Cross-origin access is simply the javascript code of website A tries to access website B, includingSubmitted content and retrieved content; For example, you want to execute JS objects on A page of website B from website A, or use JS to parse dom elements on A page of website B in website.; this cross-origin access problem occurs generally when pages of different domains are embedded in iframe, or Ajax requests are sent to different domains;
  2. For security reasons, cross-origin access is disabled by various browsers by default.It is not allowed to reference JS files of other domains on the page, and the function in the introduced JS file can be freely executed.This is personally important!
  3. Cross-origin judgment rules:Domain Name, protocol, PortIf one of the three is different, a cross-domain problem will occur. We often say that cross-domain problems generally refer to different domain names, because this scenario has the highest probability and there are some solutions to it; for example, the cross-origin problem of second-level domain names in the taobao.com domain mentioned above;
  4. For cross-domain issues with different primary domains or different protocols (such as https and http) (for example, if the * .taobao.com domain wants to access the content in the * .baidu.com domain ), it is completely impossible to solve the problem from the Web terminal. It can only be solved through the server Proxy solution;
  5. Common page control dom elements for different domains include:
    Window. location can be set but cannot be read. Access to other location attributes and methods is prohibited;
    Document. href can be set but cannot be read. Access to other document attributes and methods is prohibited;
    <Iframe> src can be set but cannot be read;
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.