Skip to main content

How to Detect browser tab state

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.

Reference:

Document - Web APIs | MDN