DEV Community

Michael Burrows
Michael Burrows

Posted on • Originally published at w3collective.com

Detect idle or active browser tabs with the Page Visibility API

In this tutorial we’ll be using the Page Visibility API to detect if a browser tab is idle (not currently being viewed) or active. To get an understanding of how the API works we’ll use it to pause a video when a tab becomes idle.

Let’s get started by setting up a HTML5 video player:

<video id="video" width="300" controls>
  <source
    src="https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4"
    type="video/mp4" />
  <p>Your browser doesn't support HTML video playback!</p>
</video>
Enter fullscreen mode Exit fullscreen mode

Now for the JavaScript functionality that’ll make use of the Page Visibility API. We first need to define an EventListener that calls a toggleVideoPlayback function when the Page Visibility visibilitychange event has been fired:

document.addEventListener("visibilitychange", toggleVideoPlayback);
Enter fullscreen mode Exit fullscreen mode

Now let’s create the toggleVideoPlayback function:

const toggleVideoPlayback = () => {
  const video = document.getElementById("video");        
  return document.hidden ? video.pause() : video.play();           
};
Enter fullscreen mode Exit fullscreen mode

This function checks the status of document.hidden. If this equals true the video will pause and if it equals false the video will resume playing. You can go ahead and test this code in browser now, note the timestamp when you navigate to another tab whilst the video is playing to confirm the video has been paused when you return.

That’s all for this tutorial. You should now have an understanding of how the Page Visibility API works. If you’re interested in learning about some of the other uses for the Page Visibility API the MDN Web Docs is worth checking out.

Latest comments (1)

Collapse
 
faaktap profile image
Fakie Tap

Thanks! Great and concise explanation.