HTML5 Web Storage

简介

 

HTML5 web storage, better than cookies.

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

 

 

1. 发展过程:

 

HTML5 Web Storage_第1张图片

 

 

2. 浏览器支持情况:

 

HTML5 Web Storage_第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");  // store
localStorage.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.例子

 

HTML5 Web Storage_第3张图片

 

 

在google resource中查看:removeItem后改记录消失

HTML5 Web Storage_第4张图片

 

简单页面访问计数:

使用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

 

参考:http://www.w3schools.com/html/html5_webstorage.asp

       http://www.cnblogs.com/xiaowei0705/archive/2011/04/19/2021372.html

 

 

 

 

 

你可能感兴趣的:(html5)