How to Check if Browser Tab is Active using Page Visibility API in Javascript

In this tutorial, you will learn how to check if browser tab is active using page visibility API in javascript.  With the help of Page Visibility API, you can detect if the user is actually active on your website or not.

A good example can be downloading websites which offers free and premium plan.  If you are a premium user, then your download will start without any waiting period.  But if you are a free or regular user, then you have to wait for certain seconds before downloading can start.

For instance, they will ask you to wait for 30 seconds before downloading can start and you might think why not just watch some youtube video in another tab and when 30 seconds will pass, you can start your downloading.  But it would not happen since they will detect that you are not active on website and the counter will freeze as soon as you switch tabs and it will resume when you come back.

This whole thing is achieved using Page Visibility API. I have explained the same scenario in this tutorial.  HTML and Javascript code is given below.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div style="margin-top: 20px; text-align: center;">
        <h1>0</h1>
    </div>


    <script src="script.js"></script>
    
</body>
</html>

Javascript

let counter = document.querySelector('h1');


window.addEventListener('DOMContentLoaded', () => {
    startCounter();
})

let intervalId;
let counterValue = 0;

function startCounter(){
    intervalId = setInterval(() => {
        counterValue++;
        counter.innerText = counterValue
    }, 1000);
}

function stopCounter(){
    clearInterval(intervalId);
}

document.addEventListener('visibilitychange', () => {
    if(document.hidden){
        stopCounter();
        return;
    }

    startCounter();
})

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •