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 scheme creates A Proxy Program (possibly any server program such as ASP and servlet) on the server side of Domain ), the page JS 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, finally, return the data to the page JS using the 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:
Copy codeThe 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 codeThe Code is as follows:
Public class Proxy extends ....... {
... DoGet (........) {
HttpClient client = ......;
GetMethod get = new GetMethod ("www.baidu.com/xxxxx.do"); // access the link of 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
}
}
}

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;

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.