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?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With