Browser - Web API - Local Storage

> (World Wide) Web - (W3|WWW) > Web - Browser

1 - About

Window/localStorage of the web api

The localStorage property allows you to access a local Storage object.

Advertising

3 - Charactertistic

  • data stored in a localStorage object has no expiration time
  • you cannot list all keys, you need therefore to know the key
  • Pages on other domains can't access the same storage objects.

data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.

4 - Example

  • Listen to storage event on other page whenever a change is made to the Storage object. It won't work on this page
window.addEventListener('storage', function(e) {  
  console.log( e.key );
  console.log( e.oldValue );
  console.log( e.newValue );
  console.log( e.url );
  console.log( JSON.stringify(e.storageArea) );
});
  • Set/Get
let key = 'key';
 
// value is null if the key is not found
if(!localStorage.getItem(key)) {
  localStorage.setItem(key, 'Default');
} 
 
// value may be null if the key is not found
let value = localStorage.getItem(key);
console.log('The value of the key is '+value )

5 - Management

5.1 - Show

The devtool can show you the local storage.

Advertising

5.2 - Set

localStorage.setItem(key, value);
// or
localStorage.key = value;
// or
localStorage[key] = value;

5.3 - IsSet

  • value is null if the key is not found
if(!localStorage.getItem(key)) {
  // Not set
  localStorage.setItem(key, 'Default');
} 

5.4 - Get

  • value may be null if the key is not found
  • You get always a string. test the string in predicate then otherwise you got a boolean problem. !'false' is false and not true.
let keyValue = localStorage.getItem(key);
// or
let keyValue = localStorage.key;
// or 
let keyValue = localStorage[key];

5.5 - List

This is not possible to list all key from the Web API.

Brower extension such as chrome.storage can do that but this is only for plugin.

5.6 - Remove

  • one
localStorage.removeItem(key);
  • all
localStorage.clear();
Advertising

5.7 - Listen

Storage event is a way for other pages on the domain using the storage to sync any changes that are made.

This won't work on the same page that is making the changes

  • Listen to to storage event on other page whenever a change is made to the Storage object
window.addEventListener('storage', function(e) {  
  console.log( e.key );
  console.log( e.oldValue );
  console.log( e.newValue );
  console.log( e.url );
  console.log( JSON.stringify(e.storageArea) );
});

6 - Documentation