Web Storage

DOM Storage は Cookie の代わりとなるもので、より大容量で、より安全かつ簡単に情報を保存できるように設計されています

Basic concepts

sessionStorage

sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).

localStorage

localStorage does the same thing, but persists even when the browser is closed and reopened.

localStorage

Setting values in storage

function populateStorage() {
  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
  localStorage.setItem('font', document.getElementById('font').value);
  localStorage.setItem('image', document.getElementById('image').value);

  setStyles();
}

json

基本的にはstringのkeyとvalueなので、jsonを保存する際にはJSON.stringify(object)を使うこと

return localStorage.setItem(namespace, JSON.stringify(data));

またgetItemを利用するときにはこのように書く

var store = localStorage.getItem(namespace);
return (store && JSON.parse(store)) || [];

clear

localStorage.clear()

function populateStorage() {
  localStorage.setItem('bgcolor', 'red');
  localStorage.setItem('font', 'Helvetica');
  localStorage.setItem('image', 'myCat.png');

  localStorage.clear();
}

remove

localStorage.removeItem(keyName);

function populateStorage() {
  localStorage.setItem('bgcolor', 'red');
  localStorage.setItem('font', 'Helvetica');
  localStorage.setItem('image', 'myCat.png');

  localStorage.removeItem('image');
}

references

results matching ""

    No results matching ""