How to detect browser tab is active JavaScript

Tabbed browsing 

Most of the browser support Tabbed browsing so modern browsers have provided a way to detect if tab has focus or switched, HTML 5 provides Page Visibility API
to do this.

Simple script to deal with most of the modern browser like Firefox, Google chrome etc.

var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];

how to call the function

 document.title = vis() ? 'Active' : 'Not Active';

You can check the title to verify that given script is working or not. The title of the page changes accordingly.

Tab browsing

Tab browsing

Tab browsing


You can use this to to stop video when user looses the focus. You can also use this script to calculate the number second that user spend in your website.

The following two tabs change content below.
Umar Farooque Khan is Software developer and professional blogger serving Worldwide on freelancer and ODesk platform to show the capability of his skills. He is the founder of The main purpose of this site is sharing and exchanging of Knowledge related to the recent technologies.