How to Detect If the Browser Tab Is Active or Not Using JavaScript?

Browser tab being active can mean two different things:

  1. Has the user switched to another tab/window?
  2. Has the window lost focus? For example, by clicking on the browser frame (such as in the address bar, the web console, etc.), or when a browser dialog shows (such as print, find, alert, confirm, etc.), etc.

If you're looking for the first, then you should consider using the Page Visibility API. For the second, you should consider using window focus and blur events.

Using the Page Visibility API

Using the Page Visibility API, you can listen for the visibilitychange event on the document object to see if the document is visible or hidden (i.e. whether the user switched to another tab or window). For example:

document.addEventListener('visibilitychange', function (event) {
    if (document.hidden) {
        console.log('not visible');
    } else {
        console.log('is visible');
    }
});

Although, this has good browser support, you may have to use vendor prefixes for the event name and the document.hidden property as shown in the example on MDN.

Using window focus and blur Events

You can use the focus and blur events on the window object to check if the window is still active like so:

window.addEventListener('focus', function (event) {
    console.log('has focus');
});

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

Please be aware of the fact that the window blur event is not only triggered when the user switches the browser tab, but anytime the window loses focus. For example when clicking on the browser frame (such as in the address bar, the web console, etc.), when a browser dialog shows (such as print, alert, confirm, find, etc.), etc. If this is not the behavior you're looking for then perhaps you should consider using the Page Visibility API instead.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.