Table of Contents

What is the Browser Local Storage? (Web API)

About

localStorage 1) is a browser/client side data storage mechanism.

It's one of the two web storage (key/pair) api and is part of the web api

The localStorage property allows you to access a local Storage object and therefore it implements all the functions of the Storage API (interface).

Browser Local Storage Devtool

Example

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) );
});
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 )

Characteristic / Security / Access

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

localStorage is protected by the same-origin policy. Any code that is not from the same origin cannot access the same data.

Use cases

Management

Show

The devtool can show you the local storage by origin

Browser Local Storage Devtool

Length

console.log("There is "+localStorage.length+" key pairs in your local storage");

Set

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

IsSet

if(!localStorage.getItem(key)) {
  // Not set
  localStorage.setItem(key, 'Default');
} 

Get

let keyValue = localStorage.getItem(key);
// or
let keyValue = localStorage.key;
// or 
let keyValue = localStorage[key];
// or where i is the position (localStorage.length gives you the length of a localStorage)
let keyValue = localStorage.key(i);

List

console.log("There is "+localStorage.length+" key/pair that are:")
for(var i =0; i < localStorage.length; i++){
  var key = localStorage.key(i);
  var item = localStorage.getItem(key)
  console.log("  - "+(i+1)+" : "+key+" : "+JSON.stringify(item).substr(0,30));
}

Remove

localStorage.removeItem(key);
localStorage.clear();

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

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) );
});

Support

localStorage is not defined

You may get this error when javascript is running on Node and not in the browser.

To make your script, Node proof, add this following condition:

if (typeof window != 'undefined') {
  // whatever with localstorage
  window.localStorage.setItem(key, JSON.stringify(state));
}

Documentation