Borislav Hadzhiev
Mon Jan 10 2022·2 min read
Photo by Micah Hallahan
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.
<!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.
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.
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.
The visibilitychange
event also fires if: