Javascript cross-origin Access Solution

Source: Internet
Author: User
Tags in domain to domain

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
The page Js of Domain A needs to access the Link under Domain B to obtain data. This solution creates a proxy on the server side of Domain.Program(It may be any server program such as ASP or servlet). js on the page of Domain A directly calls the proxy program in this 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 JS page through proxy.
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:

CopyCode The Code is as follows: <SCRIPT type = "text/JavaScript"> <! --
VaR Surl = "http://Jipiao.taobao.com/proxy.do"; // The proxy address in this domain
VaR callback =
{
Success: function (RES) {alert (res. responsetext );},
Failure: function (RES) {alert ('failure ');},
Argument :{}
}
Yahoo. util. Connect. asyncrequest ('get', Surl, callback, null );
// --> </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: copy Code the code is as follows: public class proxy extends ....... {
... doget (........) {
httpclient client = ......;
getmethod get = new getmethod ("www.baidu.com/xxxxx.do"); // link to access Domain B
int statuscode = client.exe cutemethod (get);
If (statuscode! = Httpstatus. SC _ OK) {
byte [] responsebody = get. getresponsebody ();
string res = new string (responsebody);
httpresponse. getwriter (). write (RES); // return data to Domain A
}< BR >}

Solution 2: Use the script Tag:
Write an empty script tag in the head of the domain a page http://Jipiao.taobao.com/test.htm:Copy codeThe Code is as follows: <HTML>
<Head>
<SCRIPT id = "remotescript" type = "text/JavaScript" src = ""/> <! --
<Head>
<Body>
<SCRIPT type = "text/JavaScript">
VaR remotescript = Document. getelementbyid ("remotescript ");
Remotescript. src = "www.baidu.com/xxxxx.do"; // link of Domain B
Alert (remote. Test); // use JSON data returned by Domain B
Alert (F [0]);
// --> </SCRIPT>
</Body>
</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:Copy codeThe Code is as follows: <HTML>
<Head>
<Head>
<Body>
<SCRIPT type = "text/JavaScript"> <! --
Document. Domain = "taobao.com ";
VaR remotehtml = Document. getelementbyid ("remotehtml ");
Remotehtml. src = "promotion.taobao.com/xxxx.htm"; // access the link of Domain B
VaR document = remotehtml. contentdocument; // you can use documentto operate the xxx.htm data on the page in Domain B.
// --> </SCRIPT>
<IFRAME id = "remotehtml" src = "" style = "diapay: none" style = "diapay: none"/>
</Body>
</Html>

Note: here the http://promotion.taobao.com/xxxx.htm page also needs to set document. Domain = "taobao.com", this method can work.
This IFRAME method is not suitable for cross-domain communication between different parent domains because it sets document. domain can only be set to its own parent domain, rather than other domains. For example, jiapiao.taobao.com can only be set to document. domain = "taobao.com", not document. domain = "Baidu.com ";
The three solutions listed here have their respective advantages 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:
Cross-origin access is simply the JavaScript code of website a tries to access website B, including submitting content and obtaining 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;
For security reasons, cross-origin access is disabled by various browsers by default. However, the browser does not prohibit reference of JS files in other domains on the page, and can freely execute the function in the introduced JS file. This is vital to me!
Cross-origin judgment rules are used to compare domain names, protocols, and ports. If one of the three is different, a cross-origin problem occurs; the cross-domain problem we often refer to is generally different domain names, because this scenario has the highest probability and there are some solutions; for example, the cross-domain problem of second-level domain names in the taobao.com domain mentioned above;
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;
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;

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.