Scenario is My application is open on 2-3 different tabs and i am storing some data in local storage of browser. I want to update the data if one to tabs closes and want to clear the local storage if whole browser closes.
Hi Ajay,
Browsers don't natively distinguish between closing a single tab vs closing the entire browser, both triggers standard unload events.
Could you please clarify, do your open tabs need to sync this data in real time with each other or do you only need to clear it when the tab exits?
Regards,
Abhinav
Hi Abhinav Thanks for the response.And yes Open tabs need to sync this data in real time with each other and only clear the data when browser is closed.
Thanks for clarifying — that makes the requirement much clearer.
Since browsers don't natively distinguish between a tab close and a full browser close, you'll need a combination of two browser APIs to achieve what you want: localStorage for cross-tab communication and sessionStorage for detecting whether the browser itself has been fully closed.
Here's the approach:
The Core Idea
Step-by-step Logic
On tab open — add a unique tab ID (e.g., a timestamp or random ID) to a list of active tabs stored in localStorage. Also store this tab's ID in sessionStorage so it's tied to this tab only.
On tab close (beforeunload or pagehide event) — remove this tab's ID from the active tabs list in localStorage. If the list becomes empty after removal, clear the localStorage data entirely.
For real-time sync across tabs — use the storage event on window. This event fires in all other open tabs whenever localStorage is modified, allowing each tab to react immediately to changes made by another tab.