React Js Detect user switches tabs or leaves the page
React Js Detect user switches tabs or leaves the page:In React.js, you can detect when a user switches tabs or leaves the page by utilizing the
visibilitychange
event provided by the Document Object Model (DOM). By attaching an event listener to the visibilitychange
event, you can trigger specific actions when the visibility state changes. For example, you can pause or stop ongoing processes, display a warning message, or save the user's progress.This event is fired when the user switches tabs, minimizes the window, or switches to a different application. Handling this event effectively allows you to provide a better user experience and maintain application state accordingly.
written
reviewed
updated
Thanks for your feedback!
Your contributions will help us to improve service.
How can React.js detect when a user switches tabs or leaves the page?
The provided code demonstrates how to detect if a user switches tabs or leaves the page in a React.js application. It utilizes the useEffect
hook to add an event listener for the visibilitychange
event. When the event is triggered and the document becomes hidden (document.hidden
is true
), the message state is updated to "Goodbye, world!" indicating that the user has switched tabs or left the page. When the user comes back to the page, the message state is updated to "Welcome back!"
Output of React Js Detect user switches tabs or leaves the page
Before Leave Page
After Leave Page
Ad