1, Origin
The source consists of the following three parts:
- The domain name
- port
- agreement
Two urls are homologous only if all three are the same.
Down on the link “www.example.com/page.html” to compare:
Compared to the URL | The results of | why |
---|---|---|
m.example.com/page.html | Different source | Domain name is different |
www.example.com/page.html | Different source | Agreement is different |
www.example.com:8080/page.html | Different source | Different ports |
www.example.com/page3.html | homologous | Same domain name, same port, same protocol |
2. Same-origin policy
The browser’s same-origin policy is a security feature that restricts how documents or scripts loaded from the same source can interact with resources from another source. This is an important security mechanism for isolating potentially malicious files. So the JS script under a.com uses Ajax to read the file data inside B.com will report an error.
Which are restricted by the same origin policy
For browsers, in addition to DOM, cookies, and XMLHttpRequest, some third-party plug-ins loaded by browsers also have their own same-origin policies. Some of the most common plug-ins, such as Flash, have their own control policies.
So, to experiment with the same-origin policy restriction, you can write an Ajax request, such as 127.0.0.1:80 to request a.js 127.0.0.1:8080;
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> var XHR = new XMLHttpRequest(); xhr.open('get'.'http://127.0.0.1:8080/index.js');
xhr.send(null);
xhr.onreadystatechange = function() {if(xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
alert(xhr.responseText);
}
}
</script>
</html>
Copy the code
And then we get an error, we have the same origin policy constraint.
What is cross-domain
When I say cross domain, I mean cross source. Cross-domain is a general term, and we know from the above that because of the same origin policy, different sources can’t interact with each other. So cross-domain is a general term for solving interactive problems such as initiating requests, requesting data, sending data and communication between different sources.
In the browser, tags such as
You can use these tags to load resources across domains, but GET requests that return data cannot be retrieved by JS.
Note: global properties, methods, etc. in js files can be retrieved from
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="http://127.0.0.1:8080/index.js"></script>
<script type="text/javascript">
window.onload = function(){
say();
}
</script>
</body>
</html>
Copy the code
127.0.0.1:8080 index. Js
function say(){
var app = document.getElementById('app');
app.innerHTML = "I am a method mounted on a Window object, so I can get me!";
}
Copy the code
5. Jsonp is cross-domain
What exactly is JSONP cross-domain? In fact, JSONP and JSON have no relationship, there is no similarities, we all know that JSON is a data format, and THE reason why JSONP is called JSONP, I think it is related to its request, generally get JSON format data.
If all of these tags can make cross-domain requests, then why can only use
For example, the index.html page in 127.0.0.1 loads a :
function say(){
console.log("666");
}
say();
Copy the code
When the 127.0.0.1/index.html page is opened, the
So JSONP takes advantage of this. Let’s start with an example of JSONP. 127.0.0.1 json. HTML:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>JSONP</h1>
</body>
<script >
function say(data){
alert(data);
}
</script>
<script src="Http://127.0.0.1:8080/index.php? callback=say"></script>
</html>
Copy the code
127.0.0.1:8080 index.php:
<? php$data = array(
'name'= >'zdx'.'sex'= >'man'.'age' => 18
);
$callback = $_GET['callback'];
echo $callback . '(' . json_encode($data).') '; ? >Copy the code
When accessing jsonp.html, the
So understand, jSONP is need backend support, need to use, and there is a security risk about JSONP, the data is directly executed, so as long as change the function of the same name, then how to manipulate the data can be. You can also modify parameter values to attack the server by modifying the data sent to it.
Note: This method can only initiate GET requests, and requests sent through JSONP are sent with cookies.
Vi. CORS Cross-domain (Cross-domain resource sharing)
Cross-origin Resource Sharing (CORS) defines how browsers and servers should communicate when they must access cross-source resources. The basic idea behind CORS is to use custom HTTP headers to let the browser communicate with the server to determine whether a request or response should succeed or fail.
Note: This method is not supported by Internet Explorer 8, but is partially supported by Internet Explorer 8-10.
This requires server and front end coordination, or back end and front end coordination. Can see Ruan teacher: cross-domain resource sharing CORS details
PHP is used as an example. Simply add a response header(‘ access-Control-allow-origin :http://127.0.0.1’) to the PHP file to be requested. Allow all requests from http://127.0.0.1. 127.0.0.1:8080 index. PHP:
<? php header('Access - Control - Allow - Origin: http://127.0.0.1');
echo "I'm CORS from across domains!"; ? >Copy the code
And then there’s the front end. IE10 and later, Firefox 3.5+, Safari 4+, Chrome, Safari for iOS, and WebKit for Android all implement native support for CORS through XMLHttpRequest objects. 127.0.0.1:80 index. HTML:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> var XHR = new XMLHttpRequest(); xhr.open('get'.'http://127.0.0.1:8080/index.php');
xhr.send(null);
xhr.onreadystatechange = function() {if(xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
alert(xhr.responseText);
}
}
</script>
</html>
Copy the code
Ie8-ie9 implements CORS through XDR objects. The code for index.html based on XDR is as follows:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"</title> </head> <body> <h1> </h1> var XDR = new XDomainRequest(); xdr.onload =function(){
console.log(xdr.responseText);
};
xdr.open("get"."HTTP: 127.0.0.1:8080 / index. PHP");
xdr.send(null);
</script>
</body>
</html>
Copy the code
Note: CORS can initiate GET and POST requests, but the sent request will not be sent with cookies by default, nor will it accept cookies sent from the backend.
If you want to send a cookie with it. Add header(‘ access-Control-allow-credentials :true’) to 127.0.0.1:8080 index.php; Header, then var XHR = new XMLHttpRequest() in 127.0.0.1:80 index.html; Add xhr.withCredentials = true;
Document. Domain domain
The same origin policy considers that the domain and subdomain belong to different domains. For example: XXX. XXX. XXX. XXX. XXX. XXX. XXX. XXX. XXX. XXX. XXX. XXX. XXX. You can set document.domain=’a.com’ and the browser will assume that they are all the same source. To communicate between any of these two pages, both pages must be set documen.damain=’a.com’.
Characteristics of this method:
- The domain name can be used only between the parent domain name and child domain name. If the domain name xxx.child1.a.com is set to a.com, it cannot be set to child1.a.com.
- There are security issues. When one site is attacked, another site can cause security vulnerabilities.
- This method only works with Cookie and iframe Windows.
Let’s simulate a communication between a.com and Child1.a.com. If you want to test on the host, please change the host, etc., all access to the host port 80, not here. a.com index.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> homepage </h1> <script> document.domain ='a.com';
</script>
<iframe src="http://child1.a.com/index1.html" frameborder="0"></iframe>
</body>
</html>
Copy the code
child1.a.com index.php
<? phpecho "I came down from document.domain!"; ? >Copy the code
child1.a.com index1.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>child</h1>
<script>
document.domain = 'a.com';
var xhr = new XMLHttpRequest();
xhr.open('get'.'http://child1.a.com/index.php');
xhr.send(null);
xhr.onreadystatechange = function() {if(xhr.readyState == 4 && xhr.status >= 200 && xhr.status <= 300 || xhr.status == 304){
alert(xhr.responseText);
}
}
</script>
</body>
</html>
Copy the code
Note: This method can make GET and POST requests. Cookies are not sent with the request, and cookies sent from the back end cannot be accepted
HTML5 postMessage method
This is a new method for HTML5. This method allows a script on one page to send data to a script on another page, regardless of whether the script is cross-domain. Calling postMessage() on a window object asynchronously fires the onMessage event on the window, which then fires the defined event handler. Scripts on one page still cannot directly access methods or variables on the other, but they can safely communicate via messaging technology.
For example, a page with a parent page of 127.0.0.1:80 sends data to a child page of 127.0.0.1:8080:127.0.0.1:80 index.html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> Parent page </h1> <iframe ID ="iframe" src="http://127.0.0.1:8080/ty/index6.html" frameborder="0"></iframe>
</body>
<script>
window.onload = function(){
var wd = document.getElementById('iframe').contentWindow;
wd.postMessage('I came through the postMessage method! '.'http://127.0.0.1:8080');
}
</script>
</html>
Copy the code
127.0.0.1:8080 index. HTML
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Document</title> </head> <body> <h1> </h1> </body> <script> window.adDeventListener ("message", receiveMessage, false);
function receiveMessage(event)
{
alert(event.data)
}
</script>
</html>
Copy the code
Then go to: 127.0.0.1:80/index.html and get the desired result, which is usually used for two Windows communication.
HTML5 WebSocket
Modern browsers allow scripts to connect directly to a WebSocket address regardless of the same origin policy. However, when using the WebSocket URI, inserting the Origin header in the request identifies the source of the script request. To ensure cross-site security, the WebSocket server must compare header data against the source list in the whitelist that is allowed to accept requests.
Because this needs the back end support, and is more complex, here will not give examples, interested can go to the information.
Here is a ruan teacher’s Websocket tutorial: Websocket tutorial
Ten, the window name
The window object has a name attribute that has one characteristic: That is, during the life cycle of a window, all pages loaded by a window share the same window.name, and each page has read and write permission to window.name. Window. name persists in all pages loaded by a window and will not be reset when new pages are loaded.
Therefore, this feature can be used for cross-domain communication. 127.0.0.1:80 index. HTML
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body id="data">
<h1>window.name</h1>
</body>
<script type="text/javascript">
window.name = "I'm the data from Document. name."
location.href = "http://127.0.0.1:8080/ty/index8.html";
</script>
</html>
Copy the code
127.0.0.1:8080 index. HTML
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
alert(window.name)
</script>
</body>
</html>
Copy the code
At this time, access to 127.0.0.1:80 / index. HTML, jump to 127.0.0.1:8080 / index. To get data from the HTML can accept.
11 and the location. The hash
The idea is to use location.hash to pass values. ‘# helloWorld’ in url: a.com# helloWord is location.hash. 127.0.0.1:80 index. HTML
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body id="data">
<h1>window.name</h1>
</body>
<script type="text/javascript">
location.hash = "I'm the data from Document. name."
location.href = "http://127.0.0.1:8080/index.html" + location.hash;
</script>
</html>
Copy the code
127.0.0.1:8080 index. HTML
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
alert(decodeURIComponent(location.hash.slice(1)));
</script>
</body>
</html>
Copy the code
At this time, access to 127.0.0.1:80 / index. HTML, jump to 127.0.0.1:8080 / index. To get data from the HTML can accept.
12. Proxy cross-domain
You can use an Nginx reverse proxy. For details, see Google.
These cross-domain solutions are just tools. How to use them is up to you.