Skip to the solution
EasyFrontendAsked in 20244 min read

Sync State Across Tabs Using the storage Event

3.2k views

The problem

Problem, as an interviewer would state it: "A user changes a setting (like the theme) in one open tab. How would you make every OTHER open tab of the same app pick up that change automatically, using nothing but localStorage?"

Examples:

Code
// tab A: localStorage.setItem("theme", "dark")
// tab B: window.addEventListener("storage", (e) => { if (e.key === "theme") applyTheme(e.newValue); })

Clarifying questions expected:

  • Does the tab that MADE the change need to react to its own write too, or only the others?
  • Is BroadcastChannel an acceptable alternative, or does the solution specifically need to use localStorage?
  • Should this work across tabs that were already open before the change, newly opened tabs, or both?

Code / implementation expected: Yes — real, live proof of the storage event's own real, sharp self-exclusion behavior: it does not fire in the writing document, but does fire in other real, same-origin contexts.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, live-verified proof: the storage event genuinely never fires in the writing document, but correctly fires in a separate, same-origin context — verified directly

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 4 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Promise Timeout

Continue