Detect if a Browser tab has Focus using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

Detect if a Browser tab has Focus using JavaScript #

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.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Browser tab has focus</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
function checkTabFocused() { if (document.visibilityState === 'visible') { console.log('✅ browser tab has focus'); document.body.style.backgroundColor = 'lime'; document.getElementById('box').textContent = '✅ browser tab has focus'; } else { console.log('⛔️ browser tab does NOT have focus'); document.body.style.backgroundColor = 'salmon'; document.getElementById('box').textContent = '⛔️ browser tab does NOT have focus'; } } // ✅ Add event listener document.addEventListener('visibilitychange', checkTabFocused);

We used the visibilitychange event.

The event is fired at the document when the contents of its tab have become visible or have been hidden.

If you minimize the window or switch to a different tab, you'll see the visibilitychange event fire.

The document.visibilityState property returns 2 possible values:

  • visible - the page is in the foreground tab of a non-minimized window.
  • hidden - the page content is not visible because it is in a background tab, part of a minimized window, or the operating system's screen lock is active.

If I load the example from the code snippet and switch between tabs in my browser, I can see that the visibilitychange event fires.

visibilitychange event fired

The visibilitychange event also fires if:

  • the browser tab has focus, but the browser's window is minimized.
  • the user's operating system screen lock gets activated.
Use the search field on my Home Page to filter through my more than 1,000 articles.