How to Detect browser tab state
- Using Blur and Focus Events
- Using visibilitychange Event
window.addEventListener("blur", () => {
// your logic for when user leaves the tab
});
window.addEventListener("focus", () => {
// your logic for when user is back to the tab again
});
The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not.
The opposite of blur is focus. The focus event fires when an element has received focus.
document.addEventListener("visibilitychange", () => {
// your logic to handle visible or hidden elements state
});
The visibilitychange event is fired at the document when the contents of its tab have become visible or have been hidden.
Examples
Pausing music on transitioning to hidden
This example begins playing a music track when the document becomes visible, and pauses the music when the document is no longer visible.document.addEventListener("visibilitychange", () => {
if (document.visibilityState === 'visible') {
backgroundMusic.play();
} if else (document.visibilityState === 'hidden') {
backgroundMusic.pause();
}
});
Document - Web APIs | MDN