#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

Detect idle or active browser tabs with the Page Visibility API

Last modified October 19th 2021 | GitHub Source Code [GitHub] | #js

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>Code language: HTML, XML (xml)

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);Code language: JavaScript (javascript)

Now let’s create the toggleVideoPlayback function:

const toggleVideoPlayback = () => {
  const video = document.getElementById("video");        
  return document.hidden ? video.pause() : video.play();           
};Code language: JavaScript (javascript)

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.

Related Posts

#AD Shop Web Developer T-Shirts