In this article, I'm going to show you how to check if your application is opened in an active tab.
We are going to leverage the focus
and blur
events. Focus event fires when an element receives focus, and in this case, it's fired when the user switches to the tab that has the website.
blur
on the other hand, is the opposite of focus
in that, it only gets fired when the user changes the tab or opens a different tab.
We will use a state variable to indicate that the tab has focus, or that it's the active tab.
Go to your App.js
component and add the following code snippet
import {useEffect, useState} from 'react';
export default function App() {
const [tabHasFocus, setTabHasFocus] = useState(true);
useEffect(() => {
const handleFocus = () => {
setTabHasFocus(true);
};
const handleBlur = () => {
setTabHasFocus(false);
};
window.addEventListener('focus', handleFocus);
window.addEventListener('blur', handleBlur);
// Clean up
return () => {
window.removeEventListener('focus', handleFocus);
window.removeEventListener('blur', handleBlur);
};
}, []);
return (
<div>
{tabHasFocus ? (
<h2>Tab is active</h2>
) : (
<h2>Tab is in-active</h2>
)}
</div>
);
}
handleFocus
is called when the user switches to the tab that has your website, as a result, thetabHasFocus
state is updated totrue
.handleBlur
is called when they switch tabs or minimize the browser. Similarly, thetabHasFocus
gets updated tofalse
.
Conclusion
Finally, this helps us determine whether our application is in the active tab or not.
If this was helpful, don't forget to subscribe to my newsletter to stay up to date with latest content.
Thanks!