Check if the Browser tab has Focus using React

Check if the Browser tab has Focus using React

This article will show you how to check if the Browser tab has Focus using React in some simple ways like using the window.addEventListener() or the PageVisibility library method. Let’s go into detail now.

How to check if the Browser tab has Focus using React

We can use a web browser to help you access the websites you want and perform activities such as: Searching for information, watching movies, reading books, playing games, and logging into your account. webpage,…

And browser tabs are tabs for multitasking access to different web pages. So how do we know which tab is in Focus? Let’s see how to do it below.

Using window.addEventListener() method

The addEventListener() method allows you to add event handlers to any HTML DOM elements. If you let the event listener program be a Window object, all events on the user’s window are listened to. 

Code:

import React, { useEffect, useState } from "react";
 
const App = () => {
  const[message,setMessage]=useState("");
  const onFocus = () => {
    setMessage("This browser tab is focus");
  };
 
  const onBlur = () => {
    setMessage("This browser tab is blurred");
  };
  useEffect(() => {
    window.addEventListener("focus", onFocus);
    window.addEventListener("blur", onBlur);
}, []);
  return (
    <>
      <h2>Check if the Browser tab has Focus using React | LearnShareIT</h2>
      <hr/>
      <h3>{message}</h3>
    </>
  );
};
 
export default App;

Output:

In this approach, we apply addEventListener() to the window and use functions to handle blur and focus events for the browser tab. We will use the useEffect() hook to add events to be listened to when the component mounts.

Using the PageVisibility library method

The Page Visibility API helps in saving resources and improving performance by preventing web pages from performing unnecessary tasks when the document is hidden (when the user switches tabs, it minimizes the browser). We can also use it to count access times, for example. Before coming to this method, we must pre-install this package with the npm command below.

Terminal:

npm i react-page-visibility

Code:

import React from "react";
import PageVisibility from "react-page-visibility";
 
export default class App extends React.Component {
  state = {
    isBrowserTabFocus: true,
    message: "This browser tab is in focus",
  };
  componentDidMount() {
    const { isBrowserTabFocus } = this.props;
    if (isBrowserTabFocus) {
      this.state.message.setState("This browser tab is focus");
    }
  }
 
  handleFocus = (isFocus) => {
    this.setState({
      isBrowserTabFocus: isFocus,
    });
  };
  render() {
    return (
      <PageVisibility onChange={this.handleFocus}>
        <>
          <h2>Check if the Browser tab has Focus using React | LearnShareIT</h2>
          <hr />
          <h3>{this.state.message}</h3>
        </>
      </PageVisibility>
    );
  }
}

This way, we use a built-in PageVisibility function in the installed package. The return value we can see is that the two results are the same. The component checked if the Browser tab has Focus using React, and it’s on the screen for the coder to know.

Summary

To summarize, you’re already aware of several ways to check if the Browser tab has Focus using React, but I recommend using the window.addEventListener method for easy customization. Let’s try it to get your desired results. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *