In JavaScript, the same-origin policy is an important security metric for client-side scripts (especially Javascript). That is, two pages with the same protocol (protocol), port, and host (domain name) belong to same source.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
What is the same-origin policy?
The Same Origin Policy is an important security metric for client-side scripts (especially Javascript). It first came out of Netscape Navigator 2.0, and its purpose was to prevent a document or script from being loaded from multiple different sources.
Same-origin policy means that two pages with the same protocol, port (if specified), and host (domain name) belong to the same source.
For example, http://www.example.com/dir/page.html
This URL,
protocol is http://,
domain name is www .example.com,
The port is 80 (the default port can be omitted). Its homology is as follows.
http://www.example.com/dir2/other.html:同源 http://example.com/dir/other.html:不同源(域名不同) http://v2.www.example.com/dir/other.html:不同源(域名不同) http://www.example.com:81/dir/other.html:不同源(端口不同)
Essence:
The essence is simple: it considers trusted content loaded from any site to be unsafe. When scripts that are mistrusted by the browser are run in a sandbox, they should only be allowed to access resources from the same site, not those from other sites that may be malicious.
Let’s give an example: For example, a hacker program uses IFrame to embed the real bank login page on his page. When you log in with your real username and password, his page will The content of the input in your form can be read through Javascript, so that the username and password can be easily obtained.
The purpose of the same origin policy is to ensure the security of user information and prevent malicious websites from stealing data.
Imagine a situation like this: Website A is a bank. After the user logs in, he browses other websites. What happens if other websites can read website A’s cookies?
Obviously, if the cookie contains privacy (such as the total deposit amount), this information will be leaked. What's even more frightening is that cookies are often used to save the user's login status. If the user does not log out, other websites can impersonate the user and do whatever they want. Because the browser also stipulates that submitting forms is not restricted by the same-origin policy.
It can be seen that the "same origin policy" is necessary, otherwise cookies can be shared and the Internet will be unsafe at all.
Restriction scope
With the development of the Internet, the "same origin policy" is becoming more and more strict. Currently, there are three behaviors that are restricted if they are not of the same origin.
(1) Cookie、LocalStorage 和 IndexDB 无法读取。 (2) DOM 无法获得。 (3) Ajax 请求不能发送。
Although these restrictions are necessary, they are sometimes inconvenient and affect reasonable purposes. Below, I will introduce in detail how to circumvent the above three limitations.
Avoidance method
1. Cookie
#Cookie is a piece of information written by the server to the browser. Small pieces of information can only be shared by web pages with the same origin. However, the first-level domain names of the two web pages are the same, but the second-level domain names are different. The browser allows sharing cookies by setting document.domain
.
For example, web page A is http://w1.example.com/a.html
, web page B is http://w2.example.com/b .html
, then as long as the same document.domain is set, the two web pages can share cookies.
document.domain = 'example.com';
Now, web page A sets a Cookie through a script
document.cookie = "test1=hello";
Web page B can read this Cookie.
var allCookie = document.cookie;
This method is only applicable to Cookie and iframe windows. LocalStorage and IndexDB cannot use this method.
To circumvent the same origin policy, you must use the PostMessage API introduced below.
In addition, the server can also specify the domain name of the cookie as the first-level domain name when setting the cookie, such as .example.com.
Set-Cookie: key=value; domain=.example.com; path=/
In this case, both the second-level domain name and the third-level domain name can read this cookie without any settings.
2. iframe
If the two web pages have different sources, they cannot get the other party’s DOM. Typical examples are iframe windows and windows opened by the window.open method, which cannot communicate with the parent window.
For example, if the parent window runs the following command, if the iframe window is not from the same origin, an error will be reported
document.getElementById("myIFrame").contentWindow.document // Uncaught DOMException: Blocked a frame from accessing a cross-origin frame.
In the above command, the parent window wants to obtain the DOM of the child window, and an error will be reported because of cross-origin. .
Vice versa, the child window will also report an error when getting the DOM of the main window.
window.parent.document.body // 报错
If the first-level domain name of the two windows is the same, but the second-level domain name is different, then setting the document.domain
attribute introduced in the previous section can circumvent the same-origin policy and get the DOM .
For websites with completely different origins, there are currently three methods to solve the communication problem of cross-domain windows.
2.1 Fragment identifier
片段标识符(fragment identifier)指的是,URL的#号后面的部分,比如http://example.com/x.html#fragment
的#fragment。如果只是改变片段标识符,页面不会重新刷新。
父窗口可以把信息写入子窗口的片段标识符。
var src = originURL + '#' + data; document.getElementById('myIFrame').src = src;
子窗口通过监听hashchange事件得到通知。
window.onhashchange = checkMessage; function checkMessage() { var message = window.location.hash; // ... }
同样的,子窗口也可以改变父窗口的片段标识符。
parent.location.href= target + "#" + hash;
2.2 window.name
浏览器窗口有window.name
属性。这个属性的最大特点是,无论是否同源,只要在同一个窗口里,前一个网页设置了这个属性,后一个网页可以读取它。
父窗口先打开一个子窗口,载入一个不同源的网页,该网页将信息写入window.name属性。
window.name = data;
接着,子窗口跳回一个与主窗口同域的网址。
location = 'http://parent.url.com/xxx.html';
然后,主窗口就可以读取子窗口的window.name了。
var data = document.getElementById('myFrame').contentWindow.name;
这种方法的优点是,window.name容量很大,可以放置非常长的字符串;缺点是必须监听子窗口window.name属性的变化,影响网页性能。
2.3 window.postMessage
上面两种方法都属于破解,HTML5为了解决这个问题,引入了一个全新的API:跨文档通信 API(Cross-document messaging)。
这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。
举例来说,父窗口http://aaa.com向子窗口http://bbb.com发消息,调用postMessage方法就可以了。
var popup = window.open('http://bbb.com', 'title'); popup.postMessage('Hello World!', 'http://bbb.com');
postMessage方法的第一个参数是具体的信息内容,第二个参数是接收消息的窗口的源(origin),即”协议 + 域名 + 端口”。也可以设为*,表示不限制域名,向所有窗口发送。
子窗口向父窗口发送消息的写法类似。
window.opener.postMessage('Nice to see you', 'http://aaa.com');
父窗口和子窗口都可以通过message事件,监听对方的消息。
window.addEventListener('message', function(e) { console.log(e.data); },false);
message事件的事件对象event,提供以下三个属性。
event.source:发送消息的窗口 event.origin: 消息发向的网址 event.data: 消息内容
下面的例子是,子窗口通过event.source属性引用父窗口,然后发送消息。
window.addEventListener('message', receiveMessage); function receiveMessage(event) { event.source.postMessage('Nice to see you!', '*'); }
event.origin属性可以过滤不是发给本窗口的消息。
window.addEventListener('message', receiveMessage); function receiveMessage(event) { if (event.origin !== 'http://aaa.com') return; if (event.data === 'Hello World') { event.source.postMessage('Hello', event.origin); } else { console.log(event.data); } }
2.4 LocalStorage
通过window.postMessage
,读写其他窗口的 LocalStorage
也成为了可能。
下面是一个例子,主窗口写入iframe子窗口的localStorage。
window.onmessage = function(e) { if (e.origin !== 'http://bbb.com') { return; } var payload = JSON.parse(e.data); localStorage.setItem(payload.key, JSON.stringify(payload.data)); };
上面代码中,子窗口将父窗口发来的消息,写入自己的LocalStorage。
父窗口发送消息的代码如下。
var win = document.getElementsByTagName('iframe')[0].contentWindow; var obj = { name: 'Jack' }; win.postMessage(JSON.stringify({key: 'storage', data: obj}), 'http://bbb.com');
加强版的子窗口接收消息的代码如下。
window.onmessage = function(e) { if (e.origin !== 'http://bbb.com') return; var payload = JSON.parse(e.data); switch (payload.method) { case 'set': localStorage.setItem(payload.key, JSON.stringify(payload.data)); break; case 'get': var parent = window.parent; var data = localStorage.getItem(payload.key); parent.postMessage(data, 'http://aaa.com'); break; case 'remove': localStorage.removeItem(payload.key); break; } };
加强版的父窗口发送消息代码如下。
var win = document.getElementsByTagName('iframe')[0].contentWindow; var obj = { name: 'Jack' }; // 存入对象 win.postMessage(JSON.stringify({key: 'storage', method: 'set', data: obj}), 'http://bbb.com'); // 读取对象 win.postMessage(JSON.stringify({key: 'storage', method: "get"}), "*"); window.onmessage = function(e) { if (e.origin != 'http://aaa.com') return; // "Jack" console.log(JSON.parse(e.data).name); };
3、Ajax
同源政策规定,AJAX请求只能发给同源的网址,否则就报错。
除了架设服务器代理(浏览器请求同源服务器,再由后者请求外部服务),有三种方法规避这个限制。
JSONP WebSocket CORS
3.1 JSONP
JSONP是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,老式浏览器全部支持,服务器改造非常小。
它的基本思想是,网页通过添加一个<script>
元素,向服务器请求JSON数据,这种做法不受同源政策限制;服务器收到请求后,将数据放在一个指定名字的回调函数里传回来。
首先,网页动态插入<script>
元素,由它向跨源网址发出请求。
function addScriptTag(src) { var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); } window.onload = function () { addScriptTag('http://example.com/ip?callback=foo'); } function foo(data) { console.log('Your public IP address is: ' + data.ip); };
上面代码通过动态添加<script>
元素,向服务器example.com发出请求。注意,该请求的查询字符串有一个callback参数,用来指定回调函数的名字,这对于JSONP是必需的。
服务器收到这个请求以后,会将数据放在回调函数的参数位置返回。
foo({ "ip": "8.8.8.8" });
由于<script>
元素请求的脚本,直接作为代码运行。这时,只要浏览器定义了foo函数,该函数就会立即调用。作为参数的JSON数据被视为JavaScript对象,而不是字符串,因此避免了使用JSON.parse的步骤。
3.2 WebSocket
WebSocket是一种通信协议,使用ws://(非加密)和wss://(加密)作为协议前缀。该协议不实行同源政策,只要服务器支持,就可以通过它进行跨源通信。
下面是一个例子,浏览器发出的WebSocket请求的头信息(摘自维基百科)。
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com
上面代码中,有一个字段是Origin,表示该请求的请求源(origin),即发自哪个域名。
正是因为有了Origin这个字段,所以WebSocket才没有实行同源政策。因为服务器可以根据这个字段,判断是否许可本次通信。如果该域名在白名单内,服务器就会做出如下回应。
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat
3.3 CORS
CORS is the abbreviation of Cross-Origin Resource Sharing. It is a W3C standard and is the fundamental solution for cross-origin AJAX requests. Compared with JSONP which can only send GET requests, CORS allows any type of request.
[Related recommendations: javascript learning tutorial]
The above is the detailed content of What is the same origin policy in javascript. For more information, please follow other related articles on the PHP Chinese website!