Based on the actual situation, this article discusses cross-origin Technology in two cases: first, the cross-origin Technology for different subdomains is discussed, and then the cross-origin Technology for completely different domains is discussed. If you need a friend, you can check it carefully. JavaScript is a front-end dynamic script technology that is frequently used in Web development. In JavaScript, there is a very important security restriction, called "Same-Origin Policy" (Same-Origin Policy ). This Policy imposes significant limitations on the page content that JavaScript code can access, that is, JavaScript can only access content in the same domain as the document containing it.
JavaScript, a security policy, is particularly important in Multi-iframe or Multi-Window Programming and Ajax programming. According to this policy, the JavaScript code contained in the page under baidu.com cannot access the page content under the google.com domain name; even pages of different subdomains cannot be accessed through JavaScript code. The effect on Ajax is That Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains, for example, pages under abc.example.com cannot submit Ajax requests to def.example.com.
However, when some in-depth front-end programming is required, cross-origin operations are inevitable. At this time, the "same-origin policy" is too harsh. This article summarizes some of the technologies required for cross-origin.
We will discuss cross-origin Technology in two cases: first, we will discuss cross-origin Technology for different subdomains, and then we will discuss cross-origin Technology for completely different domains.
(1) Cross-Domain Technology for different subdomains.
We will discuss the following two questions: the first is how to call JavaScript across different subdomains, and the second is how to submit Ajax requests to different subdomains.
First, let's solve the first problem. Assume that the example.com domain has two different subdomains: abc.example.com and def.example.com. Now suppose there is a page under def.example.com, which defines a JavaScript function:
The Code is as follows:
Function funcInDef (){
.....
}
We want to call the above function on a page under abc.example.com. Suppose that the page under abc.example.com we want to discuss is embedded in the page under def.example.com in the form of iframe, so we may try to make the following calls in iframe:
The Code is as follows:
Window. top. funcInDef ();
Well, we noticed that this call is forbidden by the "same-origin policy" mentioned above, and the JavaScript engine will directly throw an exception.
To implement the preceding call, We can modify the domain attribute of two pages. For example, we can add the following JavaScript code snippets to the top of the two pages above under abc.example.com and def.example.com:
The Code is as follows: