同源策略
同源定義
協(xié)議,主機,端口號三者完全相同焚辅,稱為同源。
限制范圍
如果兩個域非同源苟鸯,則有以下限制
- cookie 無法讀取
- dom 無法獲得
- ajax 請求無法發(fā)送
跨域
js 中實現(xiàn)跨域請求同蜻,有以下幾種方式
在iframe中跨域
兩個窗口一級域名相同
通過設(shè)置 document.domian 為一級域名,可以跨域
兩個窗口完全不同源
可以有以下三種方式解決跨域問題
- url.hash
url.hash是指url中 #后面的部分
父窗口把信息寫入子窗口的 url 片段
var src=sonUrl+'#'+data;
document.getElementById('myiframe').src=src
子窗口監(jiān)聽信息
window.onhashchage=checkMessage();
function checkMessage(){
var message=window.location.hash
}
子窗口向父窗口傳遞信息
function sendMessage(msg){
var hash=msg
parent.location.href=parentUrl+'#'+hash
}
- window.name
父窗口打開一個不同源的網(wǎng)站早处,將信息寫入 window.name 中
window.name=data
子窗口跳回一個與主窗口同域的網(wǎng)站
location='http://parenUrl/index.html'
主窗口可以讀取子窗口的 window.name 了
data=document.getElementByName('myiframe').contenWindow.name
- window.postMessage
otherWindow.postMessage(message,targetOrigin) 是html5新引進的函數(shù)
otherWindow 是對接受信息的 window 的引用
message 是所要發(fā)送的數(shù)據(jù)
targetOrigin 是指接收消息的源埃仪,用于限制 otherWindow
舉例來說,父窗口 a.com ,向子窗口 b.com 發(fā)送消息
var popup=window.open('b.com','title')
popup.postMessage('hello world','b.com')
子窗口像父窗口發(fā)送消息
window.opener.postMessage('nice to meet you','a.com')
子窗口和父窗口都可以通過 message 時間監(jiān)聽對方消息
window.addEventListener('message', function(e) { console.log(e.data);},false);
在 AJAX中跨域
在 AJAX 中跨域有以下幾種方式
jsonp
基本思想是跨域引用 js 腳本文件
jsonp由兩部分組成陕赃,回調(diào)函數(shù)和數(shù)據(jù)卵蛉。回調(diào)函數(shù)就是當響應(yīng)到來時在頁面中調(diào)用的函數(shù)么库,數(shù)據(jù)就是傳入回調(diào)函數(shù)中的json數(shù)據(jù)傻丝。webSocket
一種通信協(xié)議,不實用同源策略诉儒,只要服務(wù)器支持就可以跨域葡缰。cores
只要服務(wù)器實現(xiàn)了cors接口就可以跨域通信