Browser tab is active or inactive using javascript

Objective - To check whether the current browser tab is active or inactive using javascript

Using Page Visibility API: This will work only when user switched to another tab/window

document.hidden: When the page is focused, it returns false and when the page is not focused, it returns true.

document.visibilityState: It is useful to know if the document is in the background or an invisible tab, or only loaded for pre-rendering

Values it returns is read-only property -

hidden - means the current tab is not in focus.
visible - means the current tab is in focus.
unloaded - means the current tab is about to close.
prerender - means the page has been loaded but the user has not viewed the page.

<audio controls src=".files/abc.mp3"></audio>
// Handle page visibility change:
// - If the page is hidden, pause the video
// - If the page is shown, play the video
document.addEventListener("visibilitychange", () => {
  if (document.hidden) {
    audio.pause();
  } else {
    audio.play();
  }
});

Using window focus and blur events: This will work when a window or tab lost focussed example if the user switch to another app or software, another widow or tab, browser frame (such as console, address bar etc or print window), alert, search bar, confirm popup etc.

window.addEventListener('focus', function (event) {
    console.log('I am back');
});

window.addEventListener('blur', function (event) {
    console.log('bye bye');
});

Did you find this article valuable?

Support vijay khamitkar by becoming a sponsor. Any amount is appreciated!