TExcelTAD
Home › HTML › HTML Web Storage

HTML Web Storage

Web Storage lets a page save small pieces of data in the user's browser — a chosen theme, a half-written note, the contents of a shopping cart — so they are still there after a reload. It is simpler and roomier than cookies, and the data is never sent to the server automatically.

Two storage areas

Object Lifetime Shared between
localStorage Until it is deleted (by your code or the user) All tabs and windows of the same site
sessionStorage Until the tab is closed Only the current tab

Both have exactly the same methods, and each site (origin) gets its own separate storage — usually around 5 MB.

The methods

Method / property What it does
setItem(key, value) Save a value under a key
getItem(key) Read a value (returns null if missing)
removeItem(key) Delete one key
clear() Delete everything for this site
key(i) Name of the key at position i
length Number of stored keys
js
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme'); // "dark"
localStorage.removeItem('theme');

Storage can be unavailable

localStorage is not guaranteed. Private browsing modes, browser settings, full storage and sandboxed iframes can all make it throw an error the moment you touch it.

Note: ExcelTAD playgrounds run in a sandboxed iframe without same-origin access, so localStorage usually throws a SecurityError here. The examples below detect this and fall back to an in-memory object — the page still works, it just forgets everything on reload. Run the same code in a normal page and it will remember.

A safe helper looks like this:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <p id="info"></p>
  <script>
    function getStorage() {
      try {
        const s = window.localStorage;
        s.setItem('__test', '1');
        s.removeItem('__test');
        return { store: s, real: true };
      } catch (e) {
        const mem = {};
        return {
          real: false,
          store: {
            getItem: function (k) { return k in mem ? mem[k] : null; },
            setItem: function (k, v) { mem[k] = String(v); },
            removeItem: function (k) { delete mem[k]; },
            clear: function () { for (const k in mem) delete mem[k]; }
          }
        };
      }
    }
    const result = getStorage();
    document.getElementById('info').textContent = result.real
      ? 'localStorage is available — data will survive a reload.'
      : 'localStorage is blocked here — using an in-memory fallback.';
  </script>
</body>
</html>

A visit counter

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <h3 id="msg"></h3>
  <button id="again">Visit again</button>
  <button id="reset">Reset</button>
  <script>
    let store;
    try { store = window.localStorage; store.getItem('x'); }
    catch (e) { const m = {}; store = { getItem: k => m[k] ?? null, setItem: (k, v) => { m[k] = String(v); }, removeItem: k => { delete m[k]; } }; }

    function visit() {
      const count = Number(store.getItem('visits') || 0) + 1;
      store.setItem('visits', count);
      document.getElementById('msg').textContent = 'You have visited ' + count + ' time(s).';
    }
    document.getElementById('again').onclick = visit;
    document.getElementById('reset').onclick = function () {
      store.removeItem('visits');
      document.getElementById('msg').textContent = 'Counter reset.';
    };
    visit();
  </script>
</body>
</html>

Values are always strings

Web Storage only stores strings. Numbers come back as text (that is why the example uses Number(...)), and saving an object directly gives you the useless string "[object Object]". To store objects and arrays, convert them with JSON:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <input id="item" placeholder="Add a to-do">
  <button id="add">Add</button>
  <ul id="list"></ul>
  <script>
    let store;
    try { store = window.localStorage; store.getItem('x'); }
    catch (e) { const m = {}; store = { getItem: k => m[k] ?? null, setItem: (k, v) => { m[k] = String(v); } }; }

    function load() {
      try { return JSON.parse(store.getItem('todos')) || []; }
      catch (e) { return []; }
    }
    function render() {
      const list = document.getElementById('list');
      list.innerHTML = '';
      load().forEach(function (text) {
        const li = document.createElement('li');
        li.textContent = text;
        list.appendChild(li);
      });
    }
    document.getElementById('add').onclick = function () {
      const input = document.getElementById('item');
      if (!input.value.trim()) return;
      const todos = load();
      todos.push(input.value.trim());
      store.setItem('todos', JSON.stringify(todos));
      input.value = '';
      render();
    };
    render();
  </script>
</body>
</html>

JSON.stringify turns the array into text for saving; JSON.parse turns it back. Wrapping JSON.parse in try/catch protects you if the stored value is ever corrupted.

The storage event

When one tab changes localStorage, other open tabs of the same site receive a storage event. This lets you keep several tabs in sync (for example logging out everywhere at once).

js
window.addEventListener('storage', function (e) {
  console.log(e.key, 'changed from', e.oldValue, 'to', e.newValue);
});

What not to store

  • Passwords, tokens or personal data — any script running on the page can read Web Storage, so a single injected script could steal it.
  • Large data — use IndexedDB for megabytes of structured data.
  • Anything critical — users can clear storage at any time.

Tip: Prefix your keys (myapp:theme) so that different parts of a site do not accidentally overwrite each other's data.

Test yourself

What is the main difference between localStorage and sessionStorage?

  1. sessionStorage is bigger
  2. localStorage persists after the tab closes; sessionStorage is cleared when the tab closes
  3. localStorage is sent to the server
  4. There is no difference

How should you store an array in localStorage?

  1. setItem('a', myArray)
  2. setItem('a', JSON.stringify(myArray))
  3. setItem('a', myArray.length)
  4. Arrays cannot be stored

Why wrap access to localStorage in try/catch?

  1. It is always slow
  2. It can throw when storage is blocked, e.g. in private mode or sandboxed iframes
  3. It returns promises
  4. It only works in Chrome