同源策略及限制
同源策略限制了从同一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。(三相同:协议http/https,域名和端口)
- Cookie/LocalStorage和IndexDB无法读取
- DOM无法获得
- Ajax请求不能发发送
前后端如何通信
- Ajax:同源下通信方式
- WebSocket:不限制同源策略
- CORS:支持跨域通信,也支持同源通信
如何创建Ajax
- XMLHttpRequest对象的工作流程
- 兼容性处理
- 事件的触发条件
- 事件的触发顺序
var xht = XMLHttpRequest ? new XMLHttpRequest():new window.ActiveXObject('Microsoft.XMLHTTP');
var data = opt.data,
url = opt.url,
type=opt.type.toUpperCase(),
dataArr=[];
for(var k in data){
dataArr.push(k+'='+data[k]);
}
if(type === 'GET'){
url = url + '?' + dataArr.join("&");
xhr.open(type, url.replace(/\?s/g,''), true);
xhr.send();
}
if(type === 'POST'){
xhr.open(type, url, true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(dataArr.join('&'));
}
xhr.onload = function(){
if(xhr.status === 200 || xhr.status === 304){
var res;
if(opt.success && opt.success instanceof Function){
res = xhr.responseText;
if(typeof res === 'string'){
res = JSON.parse(res);
opt.success.call(xhr, res);
}
}
}else{
if(opt.error && opt.error instanceof Function){
opt.error.call(xhr, res);
}
}
}
跨域通信的几种方式
方法 | 说明 |
---|
JSONP | 动态创建<script> 标签,设置其src,回调函数在src中设置,一定要有callback=handleResponse 函数,在页面中,返回的JSON作为参数传入回调函数中,我们通过回调函数来来操作数据。function handleResponse(response){// 对response数据进行操作代码} |
Hash | Hash是url地址中#号之后的内容,其值改变不会触发页面刷新,search是url问号后面的,一旦改变会触发刷新 |
postMessage | window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机 (两个页面的模数 Document.domain设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage |
WebSocket | 不受同源策略影响https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket |
CORS | 全称是”跨域资源共享”(Cross-origin resource sharing)具体来说,就是在头信息之中,增加一个Origin字段。Origin字段用来说明,本次请求来自哪个源(协议 + 域名 + 端口)。 |
Hash详解:
var B = document.getElelementByTagName('iframe');
B.src = B.src + '#' + 'data';
window.onhashchange = function(){
var data = window.location.hash;
}
postMessage
window.postMessage(data, "http://B.com");()
window.addEventListener('message', function(event){
console.log(event.origin)
console.log(event.source)
console.log(event.data)
}, false)
WebSocket
var ws = new WebSocket('wss://a.com');
ws.onopen = function(){}
ws.onmessage = function(){}
ws.onclose = function(){}
CORS
fetch("/some/url", {
method:'get'
}).then(function(response){
}).catch(function(err){
})