Storage events

suggest change

When one document changes localStorage, other documents using the same origin and storage area receive a storage event. The document that performed the change does not receive that event.

const input = document.querySelector("input");
input.value = localStorage.getItem("user-value") ?? "";

input.addEventListener("input", () => {
  localStorage.setItem("user-value", input.value);
});

Another same-origin tab can respond to the update:

const output = document.querySelector("output");
output.value = localStorage.getItem("user-value") ?? "";

window.addEventListener("storage", (event) => {
  if (event.storageArea === localStorage && event.key === "user-value") {
    output.value = event.newValue ?? "";
  }
});

For removeItem(), event.newValue is null; for clear(), event.key, oldValue, and newValue are all null. Storage access can fail because of user settings, privacy modes, sandboxing, or quota limits, so code that writes data should handle exceptions. The API is synchronous and is intended for small amounts of string data, not high-frequency messaging or large datasets.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents