Browser - Web API - Local Storage

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

  • 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 )

Characteristic / Security

  • Data stored in a localStorage object has no expiration time.
  • Secured by origins
    • No access by pages loaded from other origins
    • Accessible by pages that are loaded from the same origin

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

  • data that needs to be accessed:
    • across windows or tabs,
    • across multiple sessions,
  • to store large (multi-megabyte) volumes of data for performance reasons

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

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

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];
// 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

  • one
localStorage.removeItem(key);
  • all
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

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

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





Discover More
Card Puncher Data Processing
Ads - Consent Management (CM - CMP)

Consent Management is a mandatory privacy process due to gdpr where a website showing a page to a EU resident needs the consent of the user in order to use their data (cookies,..) The consent box may...
Card Puncher Data Processing
Analytics - User Id (Person identity)

This page is a user identity (id). A person’s identity can be: anonymous (we don’t know anything this person yet), or named (we know something them such as an email address.) The most...
Browser
Browser - Page Sync

You can sync modifications across page by listening to the Storage event
Browser - Storage (Client Side Data)

This page is client side data (ie stateless session) in the browser. cookie local storage WebStorage - name/value pairs - Method of storing data locally...
Devtool Chrome Event Listener
DOM - Event Type (name)

An event is categorize by its type which is a property of the event object The type of an event is also known as the name of the event (Ref)...
Puppeteer Architecture
Headless browser - Puppeteer

Puppeteer is a Node library that provides a high-level API over Chrome or Chromium (ie headless chrome) Puppeteer communicate with the browser via the DevTools Protocol API The Puppeteer API is hierarchical...
Javascript - Web API (Browser Builtin API )

The Web API is a collection of javascript function (API) that a browser implements. It implements: principally the API of the DOM. and others specific browser function ... This is...
React - How to persist the local state between rendering without any library? (custom useState Hook)

This article shows you how to persist your local state (ie React state) between re-render without the use of any state library We will use the classic React counter. If you refresh the page or unmount...
Browser
Web Browser - Same-Origin Policy

User agents (such as browser) apply same-origin restrictions to code execution in order to kept data in a location accessible only to the client and the user-agent. browserHTTP client program The...



Share this page:
Follow us:
Task Runner