1.概述
Web Storage是一種在客戶端存儲數(shù)據(jù)的方法。比起Cookie,Web Storage更加安全,能夠存儲更多對象,而不僅僅是字符串;Web Storage能夠存儲更大的數(shù)據(jù),而不是像只能夠存儲幾KB數(shù)據(jù)的Cookie;Web Storage還可以減少數(shù)據(jù)在客戶端與服務(wù)器間的轉(zhuǎn)換,減少帶寬。
Web Storage的核心是是window對象的兩個子對象sessionStorage和localStorage。數(shù)據(jù)以鍵值對的形式通過這兩個對象存儲,這兩個對象都實現(xiàn)了storage接口,擁有名稱相同的屬性和方法,用法也相同。不同之處是二者的存儲時間和共享范圍。
sessionStorage數(shù)據(jù)存儲時間依賴于存儲它的瀏覽器窗口或選項卡存在的時間,共享范圍也是只在產(chǎn)生它的瀏覽器窗口或選項卡內(nèi)。
localStorage數(shù)據(jù)存儲時間要超過瀏覽器的打開時間,除非通過手動或者代碼刪除,其共享范圍是同源(origin)網(wǎng)站的頁面間。
許多瀏覽器不支持sessionStorage訪問本地文件系統(tǒng),因此要通過Web服務(wù)器使用。
Web Storage的規(guī)范允許存儲任何類型數(shù)據(jù),但在各瀏覽器實現(xiàn)上多數(shù)值允許存儲字符串文本數(shù)據(jù),但可以使用Web Storage結(jié)合JSON技術(shù)存儲非文本數(shù)據(jù)。
更高級的數(shù)據(jù)存儲方法是Web SQL Database,用于基于索引的數(shù)據(jù)庫存儲,并具有SQL查詢語言SQLite。Web SQL Database目前僅被Safari,Chrome和Opera支持。最終的規(guī)范很可能不采用這種方式。另外一種方法是IndexedDB,僅FireFox 4以上版本支持。
2.瀏覽器支持檢測
function checkStorageSupport() { //sessionStorage if (window.sessionStorage) { alert('This browser supports sessionStorage'); } else { alert('This browser does NOT support sessionStorage'); } //localStorage if (window.localStorage) { alert('This browser supports localStorage'); } else { alert('This browser does NOT support localStorage'); } }
3.Storage接口
interface Storage { //同源鍵值對的數(shù)目 readonly attribute unsigned long length; //通過索引獲取鍵,索引從0開始 getter DOM String key (in unsigned long index); //通過鍵獲取值,鍵若不存在,值將返回 null getter any getItem(in DOMString key); //存儲鍵值對,若已存在同名鍵,則值將被覆蓋。若用戶關(guān)閉了瀏覽器存儲或是已超 //過允許存儲的最大值,都將產(chǎn)生QUOTA_EXCEEDED_ERR錯誤。 set ter creator void setItem(in DOMString key, in any data); //通過鍵刪除值,不存在則什么也不做 delete r void removeItem(in DOMString key); //刪除storage中所有鍵值對,若為空則什么也不做 void clear (); };
4.讀取和存儲數(shù)據(jù)
//---------------方式一-------------- //存儲數(shù)據(jù) window.sessionStorage.setItem(‘myFirstKey’, ‘myFirstValue’); //讀取數(shù)據(jù) alert(window.sessionStorage.getItem(‘myFirstKey’)); //---------------方式二-------------- //存儲數(shù)據(jù) window.sessionStorage.myFirstKey = ‘myFirstValue’; //讀取數(shù)據(jù) alert(window.sessionStorage.myFirstKey); //---------------方式三-------------- var varKey = sessionStorage.key(index); window.sessionStorage[varKey] = new Value;
5.存儲事件
Web Storage與其它頁面、瀏覽器窗口或選項卡、Web Worker間的通信可以通過存儲事件來進行。同源的對象都可以監(jiān)聽storage事件。添加storage事件監(jiān)聽方法如下:
window.addEventListener("storage", displayStorageEvent, true);
6.StorageEvent接口
storage事件對象實現(xiàn)了StorageEvent接口,該接口的聲明如下:
interface StorageEvent : Event { readonly attribute DOMString key; readonly attribute any oldValue; readonly attribute any newValue; readonly attribute DOMString url; //該方法提供了一個對發(fā)生storage事件對象的 引用 ,這個對象可以是 //sessionStorage或localStorage readonly attribute Storage storageArea; };
6.處理最大配額
多數(shù)瀏覽器所允許的Web Storage不超過5MB,為了防止存儲數(shù)據(jù)時產(chǎn)生超出配額的限制,可以使用捕獲QUOTA_EXCEEDED_ERR異常的方法來處理,例如:
try { sessionStorage["name"] = "Tabatha"; } catch ( exception ) { if (exception == QUOTA_EXCEEDED_ERR) { // we should tell the user their quota has been exceeded. } }