HTML5 Web Storage

來源:互聯網
上載者:User

簡介

HTML5 web storage, better than cookies.

  • more secure and faster
  • data store in name/value pairs
  • the storage limit is at least 5MB

 

 

1. 發展過程:

 

 

 

2. 瀏覽器支援情況:

 

 

 

3. HTML5 Web Storage 提供如下兩種對象:

  • window.localStorage - stores data with no expiration date  沒有到期日期
  • sessionStorage - stores data for one session (data is lost when the tab is closed) 

   兩者使用沒有區別,下面使用中以localStorage舉例

 

4. 基本使用:

 

使用前應該判斷瀏覽器是否支援

if(typeof(Storage)!=="undefined")   {   // Code for localStorage/sessionStorage.  } else   {   // Sorry! No Web Storage support..  }

使用:

localStorage.setItem("name","wish");  // storelocalStorage.name="wish"; localStorage["name"]="wish";  localStorage.getItem("name");  //retrieve localStorage.removeItem("name");  //remove localStorage.clear();      //刪除所有 localStorage.key(i);   // get key
 

注意: localStorage calls toString on all stored values.  所以如果是數字等類型也會轉化為String

5.例子

在google resource中查看:removeItem後改記錄消失

簡單頁面訪問計數:

使用localStorage:

if (localStorage.visitcount)
  {
  localStorage.visitcount = Number(localStorage.visitcount) + 1; //需要轉換類型
  }
else
  {
  localStorage.visitcount= 1;
  }
document.getElementById("visitTimes").innerHTML="You have visited " +
localStorage.visitcount+ " time(s)."; 

使用sessionStorage:

if (sessionStorage.visitcount)
  {
  sessionStorage.visitcount = Number(sessionStorage.visitcount) + 1; //需要轉換類型
  }
else
  {
  sessionStorage.visitcount= 1;
  }
document.getElementById("visitTimes").innerHTML="You have visited " +
sessionStorage.visitcount+ " time(s).";

6.github上store.js

  github地址:https://github.com/marcuswestin/store.js/

  • 基於localStorage  :store.js exposes a simple API for cross browser local storage
  • 無相容性問題:store.js uses localStorage when available, and falls back on the userData behavior in IE6 and IE7
  • 儲存時不會tostring: store.js uses JSON.stringify() and JSON.parse() on each call to store.set() and store.get()

  基本使用如下:

store.set("name", "wish")  // Store store.get("name")   // Get  store.remove("username")  // Remove "name" store.clear()  // Clear all keys


相關文章

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。