PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

localStorage()

The data survies browser restart. With sessionStorage() the data survives a page restart.
 
let a = localStorage.getItem('a') ? localStorage.getItem('a') : 0;

a++;

localStorage.setItem('a', a);

if (a > 3) localStorage.removeItem('a');

console.log(a); // 1,2,3,4 ... 1,2,3,4 ...
Object-like Access    (2/4)

Object-like access

Not recommended because you can't use storage event.
 
let b = localStorage.b ? localStorage.b : 0;

b++;

localStorage.b = "b";

if (b > 3) { delete localStorage.b; }

console.log(b); // 1,2,3,4 ... 1,2,3,4 ...
Storage Event    (3/4)

Storage event

The event triggers on all window objects where the storage is accesible (except the one that caused it). a.html
 
let ab = "A message";

localStorage.setItem('ab', ab);

console.log("A window"); // A window

window.addEventListener('storage', function(event) {
    
    if (event.key != 'ab') return;
    
    ab = event.newValue;
    
    alert(ab); // B message
});
... 3 lines
 
b.html
 
let ab = "B message";

localStorage.setItem('ab', ab);

console.log("B window"); // B window
 
window.addEventListener('storage', function(event) {
    
    if (event.key != 'ab') return;
    
    ab = event.newValue;
    
    alert(ab); // A window
});
... 3 lines
 
Strings Only    (4/4)

Strings only

Both key and value must be a strings.
 
let data = {
    user: {name: "John", userId: "1"},
};

console.log(data.user); // object

localStorage.setItem("storageData", JSON.stringify(data));

let sessData = localStorage.getItem("storageData");

console.log(sessData); // string

console.log(JSON.parse(sessData).user); // object
... 3 lines
 
https://javascript.info/localstorage
Questions    
Events