Use IFRAME for cross-origin access execution of Ajax Javascript

Source: Internet
Author: User
Tags subdomain subdomain name
When a website call loads comments and other information, it encounters a problem where JavaScript cannot be executed between different domain names. It is always not displayed during loading, but it can be correctly displayed if you access another website, do not pay attention to the error message prompted by the browser:


I suddenly felt that this was the problem. After studying the problem, I thought it was quite easy, but my knowledge was still lacking. The solution was as follows:
Blocked Ajax requests
Let's verify the request blocking first. The following code is used:
Initiate three consecutive requests

[Copy this code] Code: function simplerequest ()
{
VaR request = new XMLHttpRequest ();
Request. Open ("Post", "script. ashx");
Request. Send (null );
}
Function threerequests ()
{
Simplerequest ();
Simplerequest ();
Simplerequest ();
}

When threerequests is executed, three requests with the same domain name will be sent consecutively, or the blocking effect will be viewed through statistical charts:

The last request is blocked by the first two requests.
It takes 1.5 seconds for each request. Obviously, the third request can only be executed after the first request is completed. Therefore, it takes more than three seconds to complete the execution. What we want to change is this situation.
Traditional cross-domain asynchronous request Solution
 
The only guarantee for Ajax security seems to be for cross-domain Ajax requests.
. Unless you open a webpage on the local hard disk or enable cross-domain data transmission in IE, Ajax requests to other domain names will be banned. In addition, cross-domain name judgment is very strict,
Different subdomain names, or different ports of the same domain name, are regarded as different domain names. We cannot send Ajax requests to their resources.
On the surface, it seems that there is no way to break this restriction. Fortunately, we have a savior, that is, IFRAME!
 
IFRAME does not appear in the standard, but because it is actually useful, Firefox also "has"
Line Support (similar to innerhtml ). There are already some cross-domain name asynchronous requests on the Internet, but they are not doing well. Their simple working principle is as follows:
Sets a specific page file as a proxy, and the home page uses the information of the asynchronous request through the query
String is passed to the proxy page in IFRAME. After the Ajax request is executed, the proxy page places the result in the hash of its own location.
The hash value of the SRC of IFRAME is round-robin. Once it is found that it has changed, the hash value is worth the required information.
The implementation of this method is complex and functional
Limited. In
In IE and Firefox, the URL length can be about 2000 characters. It may be enough for a common requirement. Unfortunately, if you want to transmit a large amount of data, this is far from enough.
Enough. Compared with the solution we will propose later, its only advantage may be that it can make asynchronous requests across any domain name, and our solution can only break through the limitations of subdomain names.
Now let's take a look at our practices!

Break through the limitations of sub-domain names elegantly
The key to breaking through the subdomain name limit is IFRAME.
 
IFRAME is a good thing. We can access page objects in IFRAME over sub-domain names, such
Window and Dom structure, including calling Javascript (via window object) -- we will
Set document. domain to the same. Then, initiate different requests on the pages of different subdomains and pass the results through JavaScript. Only
It is just a simple static page as a proxy.
Now let's start writing a prototype. Although it is simple, it can explain the problem.
First, write a static page as the proxy placed in IFRAME, as follows:
Subdomainproxy.html

[Copy this code] Code: <HTML xmlns = "http://www.w3.org/5o/xhtml">
<Head>
<Title> untitled page </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Document. Domain = "test.com"; function sendrequest (method, URL)
{
VaR request = new XMLHttpRequest ();
Request. Open (method, URL );
Request. Send (null );
}
</SCRIPT>
</Head>
<Body>
</Body>
</Html>

Then we will write our Home Page:

Http://www.test.com/Default.html

[Copy this code] Code: <HTML xmlns = "http://www.w3.org/5o/xhtml">
<Head runat = "server">
<Title> untitled page </title>
<SCRIPT type = "text/JavaScript" Language = "JavaScript">
Document. Domain = "test.com"; function simplerequest ()
{
VaR request = new XMLHttpRequest ();
Request. Open ("Post", "script. ashx");
Request. Send (null );
}
Function crosssubdomainrequest ()
{
VaR proxy = Document. getelementbyid ("iframeproxy"). contentWindow;
Proxy. sendrequest ('post', 'HTTP: // sub0.test.com/script.ashx ');
}
Function threerequests ()
{
Simplerequest ();
Simplerequest ();
Crosssubdomainrequest ();
}
</SCRIPT>
</Head>
<Body>
<Input type = "button" value = "request" onclick = "threerequests ()"/>
<IFRAME src = "http://sub0.test.com/subdomainproxy.html" style =" display: none ;"
Id = "iframeproxy"> </iframe>
</Body>
</Html>

When the threerequests method is executed, resources under two different domain names, http://www.test.com and http://sub0.test.com, are requested at the same time. Obviously, the last request is no longer blocked by the first two requests:

Requests with different domain names will not be blocked
Satisfactory results!
 
Although it can only break through subdomain names, it is enough, isn't it? Why do we need to force asynchronous communication between any domain names?
Why? What's more, how elegant our solutions are! In the next article, we will
The Ajax client implements a complete crosssubdomainrequestexecutor, which automatically determines whether a cross-subdomain name request is being sent and selects
Method. In this way, the asynchronous communication layer of the client is completely transparent to developers. Is there anything more pleasant in the world? :)
Notes
It may be worth mentioning the following:
I tried this idea and found that the XMLHTTPRequest object was created, you must call both the open and send methods on the IFRAME page to successfully send Ajax requests in IE and Firefox.
In
In the above example, The Request Path to the subdomain name is http://sub0.test.com/script.ashx. Note that the complete sub-domain name cannot be omitted; otherwise
In Firefox, there will be an error with insufficient permissions, and an exception will be thrown when the open method is called -- it seems that Firefox treats it as a resource of the parent page domain name.
Because browsing
The browser does not allow different domains (such as phinest.org and lab.phinest.org) and different protocols (such:

Http://phinest.org and https://phinest.org), different ports (for example: http:

Pages under phinest.org and http://phinest.org: 8080) access each other through XMLHttpRequest, which also affects different
Page JavaScript calls and control each other, but when the main domain, protocol, port is the same, by setting the document. Domain main domain of the page,
Javascript can control access between different subdomains, for example, by setting document. Domain = 'phinest. org ', http:
// Phinest.org and http://lab.phinest.org pages can communicate with each other, which also provides
XMLHttpRequest mutual access solution.
For Ajax cross-origin problems with the same primary domain, protocol, and port, it has been set very early
Document. domain is used to solve the problem, but we have never seen a successful application. The principle of this attempt is to use a hidden IFRAME to introduce the cross-domain sub-domain
As a proxy, use JavaScript to control
XMLHttpRequest to obtain data. Ajax access under different primary domains, protocols, and ports must be implemented through the background proxy.

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.