Skip to content

Instantly share code, notes, and snippets.

@squio
Last active November 21, 2025 15:19
Show Gist options
  • Select an option

  • Save squio/22d00cec940b8c5e9d893a84108eafd6 to your computer and use it in GitHub Desktop.

Select an option

Save squio/22d00cec940b8c5e9d893a84108eafd6 to your computer and use it in GitHub Desktop.
Keep track of open tabs or windows in browser
<!DOCTYPE html>
<html>
<head>
<title>Open tabs</title>
<script type="application/javascript">
window.addEventListener('storage', (event) => {
if (event.key === 'openTabs') {
console.log('openTabs changed:', event.newValue);
openTabs = JSON.parse(event.newValue || '[]');
document.querySelector('#tabCount').textContent = openTabs.length;
document.querySelector('title').textContent = `${openTabs.length} open tabs`;
}
});
window.addEventListener('beforeunload', (event) => {
console.log('beforeunload:', event);
window.sessionStorage.setItem('closedLastTab', 'true');
const thisTabId = window.sessionStorage.getItem('tabId');
const openTabs = JSON.parse(window.localStorage.getItem('openTabs') || '[]');
if (openTabs.length === 1) {
window.localStorage.removeItem('openTabs');
} else {
window.localStorage.setItem(
'openTabs',
JSON.stringify(openTabs.filter((tabId) => tabId !== thisTabId)),
);
}
});
window.addEventListener('load', () => {
const persistedTabId = window.sessionStorage.getItem('tabId');
const isSessionTabOpen = window.sessionStorage.getItem('closedLastTab') === 'false';
const openTabs = JSON.parse(window.localStorage.getItem('openTabs') || '[]');
const tabId =
persistedTabId && !isSessionTabOpen ? persistedTabId : Math.random().toString().substr(2);
window.sessionStorage.setItem('tabId', tabId);
window.sessionStorage.setItem('closedLastTab', 'false');
window.localStorage.setItem('openTabs', JSON.stringify([...openTabs, tabId]));
});
</script>
</head>
<body>
<h1>Open Tabs Demo</h1>
<h2>
Open tabs or windows: <span style="font-weight: bold; color: #c00" id="tabCount">0</span>
</h2>
<p>
This demo shows how many tabs or windows are open in the same browser. Note that private
windows all share the same local storage, so they are counted as a single Private browser
environment.
</p>
<p>
Open this page in multiple tabs or windows to see the count increase. Close a tab or window to
see the count decrease.
</p>
<p>
Note that `sessionStorage` is unique to each tab or window, unless a tab is duplicated. There
is a work around to detect this and create a new `tabId` for this case.
</p>
<script type="application/javascript">
setTimeout(() => {
const openTabs = JSON.parse(window.localStorage.getItem('openTabs') || '[]');
document.querySelector('#tabCount').textContent = openTabs.length;
}, 10);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment