Storage and history
A browser keeps two things between one page and the next: a store of strings for the origin and a list of the addresses the reader has visited. localStorage holds a value until a program removes it or the reader clears the site, and history lets a page change the address without a load. Together they are what makes a note survive a reload and a step back land where the reader left.
The four programs of this lesson write and read the store, save a draft from a text area and load it again, move through three addresses with pushState and listen for popstate, and read a stored value that is no longer JSON. They run in jsdom as the first lesson of this part showed, and one line of the first program marks the limit of that setup: jsdom keeps the store in memory for each page it opens.
localStorage on a page
localStorage has four methods and two properties: setItem, getItem, removeItem, clear, and length with key(index). Keys and values are strings, the order of the keys is the order of the writes, and a missing key gives null. The store belongs to the origin of the page, so two pages on the same host and port see the same data and a page on another host sees nothing.
The program writes three values, reads them back, removes one and prints the count and the keys at each step, then opens a second page to show what a store per page means.
The file storage.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><title>Notes</title><p>a page</p>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { window } = dom;
const store = window.localStorage;
console.log('the storage starts empty:', store.length);
store.setItem('theme', 'dark');
store.setItem('draft', 'a first line');
store.setItem('count', 2);
console.log('after three writes:', store.length);
console.log('the theme:', store.getItem('theme'));
console.log('a number is stored as text:', store.getItem('count'), typeof store.getItem('count'));
console.log('a missing key:', store.getItem('missing'));
console.log('the key at 0:', store.key(0));
store.removeItem('theme');
console.log('after the remove:', store.length, store.getItem('theme'));
const second = new JSDOM(html, { url: 'http://localhost/' });
console.log('a second page of the program starts empty:', second.window.localStorage.length);
node storage.js
the storage starts empty: 0
after three writes: 3
the theme: dark
a number is stored as text: 2 string
a missing key: null
the key at 0: theme
after the remove: 2 null
a second page of the program starts empty: 0
The number went in as a number and came back as the string 2, because a store of text does the conversion on the way in. The last line is a property of the tool and not of the browser: a real browser keeps the origin store on disk and a second tab sees the same data, while jsdom gives each page of a program an empty store unless the program passes the same one in.
A draft that comes back
The usual use of the store is a draft: the text of a text area that a reader would lose on a reload. The page writes it on a click and reads it when it opens, and the value that goes in is JSON.stringify of an object, so the store holds one string with a shape the program decides. An empty draft removes the key instead of storing an empty string, which keeps getItem able to answer null for nothing to restore.
The program types two lines, clicks save, reads the store back into the field and saves an empty value to show that the key goes away.
The file draft.js:
const { JSDOM } = require('jsdom');
const html = [
'<!doctype html>',
'<body>',
'<textarea id="draft"></textarea>',
'<button id="save">save</button>',
'<p id="state"></p>',
'</body>',
].join('');
const dom = new JSDOM(html, { url: 'http://localhost/notes/new' });
const { window } = dom;
const { document } = window;
const area = document.querySelector('#draft');
const save = document.querySelector('#save');
const state = document.querySelector('#state');
save.addEventListener('click', () => {
const text = area.value;
if (text.trim() === '') {
window.localStorage.removeItem('note-draft');
state.textContent = 'nothing to save';
return;
}
window.localStorage.setItem('note-draft', JSON.stringify({ text }));
state.textContent = `saved ${text.length} characters`;
});
area.value = 'the first line\nand a second';
save.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('the page says:', state.textContent);
console.log('the keys in storage:', window.localStorage.length, window.localStorage.key(0));
area.value = '';
const raw = window.localStorage.getItem('note-draft');
area.value = raw === null ? '' : JSON.parse(raw).text;
console.log('the draft came back in the field:', area.value.split('\n').length, 'lines');
console.log('the second line:', area.value.split('\n')[1]);
area.value = ' ';
save.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
console.log('after an empty save:', state.textContent, 'the key is gone:', window.localStorage.getItem('note-draft') === null);
node draft.js
the page says: saved 27 characters
the keys in storage: 1 note-draft
the draft came back in the field: 2 lines
the second line: and a second
after an empty save: nothing to save the key is gone: true
The draft came back with its newline and its second line, because JSON keeps the characters of a string as they are, and the empty save removed the key instead of writing null into it. A page that stores one object under one key can read the whole draft back in one call, which is the simplest shape that survives a reload.
pushState and popstate
history.pushState(state, title, url) changes the address of the page and adds an entry to the history, without a request and without a load, and replaceState changes the current entry instead of adding one. The state is any value that survives a structured clone and it comes back on the popstate event when the reader moves between entries. A page that draws its own views uses this pair to keep the address in step with the view.
The program pushes two addresses, prints the path and the history length, then raises the popstate event by hand, because a back step in jsdom is queued and the lesson prints the same output on every run. The listener receives the state of the entry that was re-entered.
The file history.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><title>Notes</title><p>a page</p>';
const dom = new JSDOM(html, { url: 'http://localhost/notes' });
const { window } = dom;
const seen = [];
window.addEventListener('popstate', (event) => {
seen.push(event.state === null ? 'null' : event.state.page);
});
window.history.pushState({ page: 'list' }, '', '/notes/list');
console.log('after the first push:', window.location.pathname, window.history.state.page);
console.log('the history length:', window.history.length);
window.history.pushState({ page: 'one' }, '', '/notes/1');
console.log('after the second push:', window.location.pathname, window.history.length);
window.dispatchEvent(new window.PopStateEvent('popstate', { state: { page: 'list' } }));
window.dispatchEvent(new window.PopStateEvent('popstate', { state: null }));
console.log('the popstate listener saw:', seen.join(', '));
window.history.replaceState({ page: 'one', saved: true }, '', '/notes/1?saved=1');
console.log('after the replace:', window.location.pathname + window.location.search, window.history.state.saved);
console.log('the address the page would ask for:', window.location.href);
node history.js
after the first push: /notes/list list
the history length: 2
after the second push: /notes/1 3
the popstate listener saw: list, null
after the replace: /notes/1?saved=1 true
the address the page would ask for: http://localhost/notes/1?saved=1
Two pushes made three entries, because the page itself was already one, and the state of each entry came back in the event. The replace kept the count at three and changed the address of the current entry, which is what a page does when it corrects a path or adds a filter to it. None of this asked the server for anything, and the last line is the address a reload would send to a server that has to answer it.
A value that has gone bad
The store holds whatever was written, and a program that changes the shape of its value meets the old one on the next visit. JSON.parse of half a value throws a SyntaxError, and a page that lets that error escape loses the whole script for a draft nobody needs. The guarded reader in the program asks for the key, checks it and parses it inside a try, so a corrupt value reads as no value at all.
The program puts a broken string under the key, parses it once without a guard to show the message, and then reads it through a function that keeps the page working.
The file corrupt.js:
const { JSDOM } = require('jsdom');
const dom = new JSDOM('<!doctype html><p>a page</p>', { url: 'http://localhost/' });
const { window } = dom;
window.localStorage.setItem('note-draft', 'half a dra');
try {
JSON.parse(window.localStorage.getItem('note-draft'));
} catch (error) {
console.log('the error:', error.name, '-', error.message);
}
function readDraft() {
const raw = window.localStorage.getItem('note-draft');
if (raw === null) {
return null;
}
try {
return JSON.parse(raw);
} catch {
return null;
}
}
console.log('the guarded reader gives:', readDraft());
window.localStorage.setItem('note-draft', JSON.stringify({ text: 'a whole draft' }));
console.log('after a good write:', readDraft().text);
node corrupt.js
the error: SyntaxError - Unexpected token 'h', "half a dra" is not valid JSON
the guarded reader gives: null
after a good write: a whole draft
The message quotes the value and the character that stopped the parser, which is enough to see what went wrong. The guarded reader turned that into null and the page went on, and the good write after it shows that the same function reads a value of the right shape. The store is shared with every script of the origin, so a page that reads it has to expect a value that it did not write.
Exercises
- Store true and read it back. Which value and which type do you get, and what is the shortest fix?
- Write ten keys and print them with a loop over length and key(index). In which order do they come out?
- Call localStorage.clear() and print the count. Which of the four methods would remove one key, and which one removes all of them?
- Push the same address twice and print history.length. How many entries did the two calls add?
- Read the state of the first entry after two pushes with history.state. Which entry does the property describe?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does localStorage hold?
Answer
Strings, under string keys
The store is text, so an object goes in through JSON and a number comes back as text.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://localhost/" }); dom.window.localStorage.setItem("count", 2); console.log(dom.window.localStorage.getItem("count"), typeof dom.window.localStorage.getItem("count"));Answer
2 string
setItem converts the value to text and getItem always answers text or null.
-
What does getItem answer for a key that was never written?
Answer
null
The store distinguishes a missing key from a stored empty string, and null is the missing one.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://localhost/" }); const store = dom.window.localStorage; store.setItem("a", "1"); store.setItem("b", "2"); store.removeItem("a"); console.log(store.length, store.getItem("a"));Answer
1 null
One of the two keys is left, and the removed one reads as the missing value null.
-
What does history.pushState change?
Answer
The address and the history, without a request or a load
The call edits the entry list of the browser, and the page draws the new view itself.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://localhost/notes" }); dom.window.history.pushState({ page: "one" }, "", "/notes/1"); console.log(dom.window.location.pathname, dom.window.history.length);Answer
/notes/1 2
The path came from the third argument, and the push added one entry to the page that was already there.
-
When does a popstate listener run?
Answer
When the reader moves to another history entry
The event belongs to a change of the current entry, which is what a back or forward step makes.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<p>a page</p>", { url: "http://localhost/notes" }); const seen = []; dom.window.addEventListener("popstate", (event) => { seen.push(event.state === null ? "null" : event.state.page); }); dom.window.history.pushState({ page: "list" }, "", "/notes/list"); dom.window.dispatchEvent(new dom.window.PopStateEvent("popstate", { state: { page: "list" } })); console.log(dom.window.history.state.page, seen.join(", "));Answer
list list
The current entry holds the pushed state, and the listener read the state of the event object.
-
How does a program store an object in localStorage?
Answer
JSON.stringify on the way in and JSON.parse on the way out
The store only carries text, and the JSON round trip is the usual way to keep a shape.
-
What does this program print?
const { JSDOM } = require("jsdom"); const html = "<p>a page</p>"; const first = new JSDOM(html, { url: "http://localhost/" }); const second = new JSDOM(html, { url: "http://localhost/" }); first.window.localStorage.setItem("draft", "a note"); console.log(first.window.localStorage.length, second.window.localStorage.length);Answer
1 0
jsdom keeps one store per page object, so a second page of the same program starts empty.
The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev