最近或多或少經(jīng)呈Γ看到跨域操作,自己也沒有有個(gè)時(shí)間去專門研究透徹這一塊盾舌,所以打算借此機(jī)會(huì)墓臭,好好研究一番,并為此寫幾篇博文妖谴,這也算鞏固一下這方面的基礎(chǔ)知識(shí)窿锉。
不過講跨域之前就有必要先了解是什么導(dǎo)致了跨域才能清求,答案就是 瀏覽器的同源策略
那么何為 "源" 呢?
首先看看RFC6454里有定義URI源的算法定義嗡载。
源包括協(xié)議窑多、域名、端口號(hào)洼滚。
標(biāo)準(zhǔn)瀏覽器下查看源的方式:location.origin
ie瀏覽器下不支持此種方式埂息,但我們可以使用“ location.protocol查看協(xié)議、location.hostname查看域名判沟、location.port查看端口號(hào) ” 來查看源耿芹。
原文給出的例子:
解決了什么是 源 下來就是什么是同源策略迹炼。
一樣來看看這篇文章的定義.
In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, host name, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.
同源策略是瀏覽器的一個(gè)安全功能砸彬,不同源的客戶端腳本在沒有明確授權(quán)的情況下,不能讀寫對(duì)方資源斯入。所以lmc.com下的js腳本采用ajax讀取szu.com里面的文件數(shù)據(jù)是會(huì)報(bào)錯(cuò)的砂碉。
? 不受同源策略限制的:
1、頁面中的鏈接刻两,重定向以及表單提交是不會(huì)受到同源策略限制的增蹭。
2、跨域資源的引入是可以的磅摹。但是js不能讀寫加載的內(nèi)容滋迈。如嵌入到頁面中的<script src="..."></script>,<img>户誓,<link>饼灿,<iframe>等。
那么現(xiàn)實(shí)生活中帝美,我們往往不能僅僅滿足于同源之間資源共享碍彭,那么如何突破同源策略呢?
一悼潭、降域
對(duì)于主域相同而子域不同的例子庇忌,可以通過設(shè)置document.domain的辦法來解決。具體的做法是可以在http://www.a.com/a.html和http://script.a.com/b.html兩個(gè)文件中分別加上document.domain = ‘a.com’女责;然后通過a.html文件中創(chuàng)建一個(gè)iframe漆枚,去控制iframe的contentDocument,這樣兩個(gè)js文件之間就可以“交互”了抵知。當(dāng)然這種辦法只能解決主域相同而二級(jí)域名不同的情況,如果你異想天開的把script.a.com的domian設(shè)為alibaba.com那顯然是會(huì)報(bào)錯(cuò)地!代碼如下:
www.a.com上的a.html
document.domain = 'a.com';
var ifr = document.createElement('iframe');
ifr.src = 'http://script.a.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
var doc = ifr.contentDocument || ifr.contentWindow.document;
// 在這里操縱b.html
alert(doc.getElementsByTagName("h1")[0].childNodes[0].nodeValue);
};
script.a.com上的b.html document.domain = 'a.com';
問題:
1刷喜、安全性残制,當(dāng)一個(gè)站點(diǎn)(b.a.com)被攻擊后,另一個(gè)站點(diǎn)(c.a.com)會(huì)引起安全漏洞掖疮。
2初茶、如果一個(gè)頁面中引入多個(gè)iframe,要想能夠操作所有iframe浊闪,必須都得設(shè)置相同domain恼布。