Xiaopei's DokuWiki

These are the good times in your life,
so put on a smile and it'll be alright

User Tools

Site Tools


it:html5_local_storage

html5 local storage

介绍

  1. 每次 HTTP 请求都会包含, 需要传输的更多了, 会减慢请求速度
  2. 每次 HTTP 请求都会包含, 不安全
  3. 容量小(limited to about 4 KB)

当前 HTML5 使用的本地储存: Web Storage

关键:

  1. 键值对
    1. 键为 String
    2. 在写入时, 值可以是任意 JavaScript 数据类型, 但储存后会变成 String, 所以在读取时, 应使用 parseInt() or parseFloat() 等做类型转化
  2. 长期储存在浏览器 (类似 cookie)
  3. 不会自动传送到远程

本地储存的未来

  1. Web SQL Database
  2. IndexedDB

Web Storage 接口

CRUD

读/写

interface Storage {
  getter any getItem(in DOMString key);
  setter creator void setItem(in DOMString key, in any data);
};
 
var foo = localStorage.getItem("bar");
// Calling getItem() with a non-existent key will return null rather than throw an exception. 
// ...
localStorage.setItem("bar", foo);
 
// Like other JavaScript objects, you can treat the localStorage object as an associative array. 
var foo = localStorage["bar"];
// ...
localStorage["bar"] = foo;

删除

interface Storage {
  deleter void removeItem(in DOMString key);
  void clear();
};
// Calling removeItem() with a non-existent key will do nothing. 

遍历

interface Storage {
  // get the total number of values in the storage area
  readonly attribute unsigned long length;
  // iterate through all of the keys by index (to get the name of each key)
  getter DOMString key(in unsigned long index);
};

监听 storage 事件

if (window.addEventListener) {
  window.addEventListener("storage", handle_storage, false);
} else {
  window.attachEvent("onstorage", handle_storage);
};
 
// The handle_storage callback function will be called with a StorageEvent object, except in Internet Explorer where the event object is stored in window.event. 
function handle_storage(e) {
  if (!e) { e = window.event; }
}

StorageEvent Object:

PropertyTypeDescription
keystringthe named key that was added, removed, or modified
oldValueanythe previous value (now overwritten), or null if a new item was added
newValueanythe new value, or null if an item was removed
url 1) stringthe page which called a method that triggered this change
1)
the url property was originally called uri. Some browsers shipped with that property before the specification changed. For maximum compatibility, you should check whether the url property exists, and if not, check for the uri property instead.
it/html5_local_storage.txt · Last modified: 2013/09/08 18:16 by admin