Track or detect number of tabs open for same website in React/Javascript

Meet Zaveri
2 min readMar 16, 2022

--

I had this scenario where I needed to figure out that how many tabs are open of same website(app) in React.js. Since I researched and came to know that there’s no official API for detecting tabs open for the same website, I needed to develop a solution using whatever JS offers from its existing API with React’s useEffect hook.

Core idea

We will use help of localStorage API. With that we will keep track of tabs open counter.

Simply to put words as: we increment counter of “tabs open” when some user opens up a new tab or decrement counter of “tabs open” when some user closes tab or browser.

Init (increment tabs open counter) setup

First, we implement the base setup for counter increment.

We check that if key( lets say tabsOpen) is available in localStorage or not. If not, then we initialize by supplying value of 1 to it. Otherwise if it's available, we simply increment its counter

const tabsOpen = localStorage.getItem('tabsOpen')
console.log('tabsOpen', tabsOpen)
if (tabsOpen == null) {
localStorage.setItem('tabsOpen', 1)
} else {
localStorage.setItem('tabsOpen', parseInt(tabsOpen) + parseInt(1))
}

Using window.onunload for detecting close event of a tab or browser window

We use window.onunload method which helps us when a user closes a tab or whole browser window. That means it programmatically captures closing of tab or window.

This is where we will decrement the tabs open counter.

window.onunload = function (e) {
const newTabCount = localStorage.getItem('tabsOpen')
if (newTabCount !== null) {
localStorage.setItem('tabsOpen', newTabCount - 1)
}
}

Demo

Final Source Code snippet

Place this code snippet into your root component (for eg. App.js) .

NOTE: Please make sure for you to test this code, you should set/delete localStorage key acc. to your values to reset in to preferable value

Thanks for reading this. I would love your feedback or criticism for this content, which helps me to structure this article even more better.

Keep hustling

--

--