HTML Web Storage

Web Storage API的出現,使得開發者可以將需要跨請求重複訪問的數據直接存儲在客戶端的瀏覽器中,還可以在關閉瀏覽器很久再次打開時恢復數據,以減小網絡流量。


Cookies vs. Local Storage

在H5之前,應用數據通常存儲在cookie中。服務器可以基於其放在cookie中的數據在不同Web頁面間追蹤用戶的信息。用戶每次訪問某個域時,cookie數據都會被來回傳送。

When a browser request a web page from a server, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

1. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

與cookies(只能設置大約4KB多數據,只要有請求涉及cookie,cookie就要在服務器和瀏覽器間來回傳送)不同的是,LS的存儲極限更大,且存儲的數據不會在網絡上傳輸。

2. 如果用戶使用設置爲“私有/隱私保護”模式的瀏覽器進行瀏覽,那麼在瀏覽器關閉後,localStorage中的值將不會保存。因爲使用了這種模式的用戶已經明確選擇不留痕跡。

3. sessionStorage,數據只在構建它們的窗口或標籤內可見。localStorage,數據可以被同源的每個窗口或標籤頁共享。

4. Storage接口方法key(index)允許獲取一個指定位置的鍵。獲取鍵後,可以用它來獲得相應的數據。

5. removeItem(key)函數用來刪除數據項。刪除數據相時,不會將原有數據作爲返回結果,與某些集和或數據框架不同。

6. clear() 函數刪除存儲列表中所有的數據,空的Storage對象調用此函數也是安全的,只是不執行任何操作。 

7. 如果用戶已關閉了網站的存儲,或存儲達到其最大的容量,此時設置數據將拋出QUOTA_EXCEEDED_ERR錯誤。

8. 只要有同源的Storage事件發生(包括SessionStorage和LocalStorage觸發的事件),已註冊的所有事件偵聽器作爲事件處理程序就會接到相應的Storage事件。該事件中包含與存儲變化有關的信息。如果是新添加的數據,則oldValue屬性值爲null,如果是被刪除的數據,則newValue屬性值爲null。


Web Storage Objects

HTML WS 提供了兩種對象用來在客戶端存儲數據:

  • window.localStorage - stores data with no expiration date (數據不會因爲瀏覽器關閉而刪除,如沒有干預,將一直有效)
  • window.sessionStorage - stores data for one session (data is lost when the tab is closed)

通常我們可以省略window對象,因爲storage對象可以從默認的頁面上下文中獲得。

使用前先檢查一下瀏覽器對WS的支持性:

if(window.localStorage/window.sessionStorage) {
    // Code for localStorage/sessionStorage.
} else {
    // Sorry! No Web Storage support..
}

localStorage

存儲和獲取:

// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
另一種寫法:

// Store
localStorage.lastname = "Smith";
localStorage['lastname'] = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;
刪除:
localStorage.removeItem("lastname");

Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!

需要注意的是,鍵/值 對總是以字符串形式存儲,使用時根據需要進行格式轉換。

if (localStorage.clickcount) {
    localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
    localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";

sessionStorage

該對象等同於 localStorage,除了它只爲一個瀏覽器會話存儲數據,也就是說,當瀏覽器窗口關閉時,數據就被刪除。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章