Web Storage

localStorage and sessionStorage

Web Storage saves key/value strings in the browser.

localStoragesessionStorage
Lifetimeuntil deleteduntil the tab is closed
Shared between tabsyes (same site)no
Sizeabout 5 MBabout 5 MB

Example

Example

Type a name and reload the page in the code runner: the value is remembered. (Storage may be blocked inside the lesson preview.)

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>
<body>

<input id="name" placeholder="Your name">
<button id="save">Save</button>
<p id="out"></p>
<script>
  const out = document.getElementById('out');
  try {
    out.textContent = 'Saved name: ' + (localStorage.getItem('name') || '(none)');
    document.getElementById('save').onclick = () => {
      localStorage.setItem('name', document.getElementById('name').value);
      out.textContent = 'Saved name: ' + localStorage.getItem('name');
    };
  } catch (e) {
    out.textContent = 'Storage is not available here: ' + e.name;
  }
</script>

</body>
</html>

Result

Note: Never store passwords or tokens that grant access in localStorage: any script on the page can read it.