← Go back to blog
Awa Dieudonne Mbuh
Aug 102 min read

Check if your application is open in an active browser tab

How to know if your application is open in the open/focused or close/inactive browser tab using React.js Hooks.
Check if your application is open in an active browser tab

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, the tabHasFocus state is updated to true.
  • handleBlur is called when they switch tabs or minimize the browser. Similarly, the tabHasFocus gets updated to false.

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!

React.js
JavaScript
Comments(0)