Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the browser tab is in focus in ReactJS

Tags:

reactjs

I have a website in ReactJS. I want to get a callback whenever my tab comes in focus or is hidden. I came across the Page Visibility API for this but I'm not able to figure out how to use it in ReactJS.

In which lifecycle method do I register the callback for this?

like image 296
Pravesh Jain Avatar asked Apr 18 '18 14:04

Pravesh Jain


People also ask

How do I know if my browser is in focus?

Use the visibilitychange event to detect if a browser tab has focus or not, e.g. document. addEventListener('visibilitychange', checkTabFocused) . The event is fired at the document when the contents of its tab have become visible or have been hidden.

How do you check if React component is focused?

To check if an element is focused in React: Set the ref prop on the element. After the element is rendered, check if the element is the active element in the document. If it is, the element is focused.

How do I check my browser type in React?

Check browser name For example, to get the browser name and version, we will import browserName and browserVersion from the library. import { browserName, browserVersion } from "react-device-detect"; If we log these two values to the console, we will see the following.


1 Answers

Just built this using hooks as of React 16.8

import React, { useEffect } from "react";  // User has switched back to the tab const onFocus = () => {     console.log("Tab is in focus"); };  // User has switched away from the tab (AKA tab is hidden) const onBlur = () => {     console.log("Tab is blurred"); };  const WindowFocusHandler = () => {     useEffect(() => {         window.addEventListener("focus", onFocus);         window.addEventListener("blur", onBlur);         // Calls onFocus when the window first loads         onFocus();         // Specify how to clean up after this effect:         return () => {             window.removeEventListener("focus", onFocus);             window.removeEventListener("blur", onBlur);         };   }, []);      return <></>; };  export default WindowFocusHandler;  
like image 64
Assaf Avatar answered Oct 04 '22 01:10

Assaf