Introducing the Page Visibility API

The Page Visibility API is useful for detecting the visibility state of the page.

We can listen to the visibilitychange event and then get the visibility state with document.visibilityState and so what we want with it.

How can you use it?

Well imagine you’re playing a video and then scroll away from it, or maybe it was part of a tabbed interface on the page. Well, this would trigger a new visibility state on the element and you can pause the video for example.

Let’s try this out with a video on this site.

Here’s a video I found on Vimeo.

Usually when people are consuming video content we want them to be watching it, but sometimes the user will move to another tab and you’ll want the video to pause at that point.

You should be aware that this is a decision which you’re taking off the user though, I know plenty of people that use YouTube as a radio so this would really irritate them.

The code for this is below


// first I load in the Vimeo video controls API and configure it. 
// This code is pulled directly from https://developer.vimeo.com/player/sdk/basics
<script src="https://player.vimeo.com/api/player.js"></script>
  <script>
    var iframe = document.querySelector('iframe');
    var player = new Vimeo.Player(iframe);
  </script>

// next we set up a event listener for the visibility change event. 
//When that occurs we check to see if the visibility state is NOT 
//visible, and if true we pause the video, it it is not true, we play the video.

<script>
document.addEventListener('visibilitychange', () => {
  if (document.visibilityState !== 'visible') {
      player.pause();
    console.log("The video is paused");
  }  else {
     player.play();
    console.log("The video is playing");
}
})
</script>

No sound on Firefox

One strange thing I found with this is that Firefox no longer plays the sound when I use the &api=1 on the video embed options. I’m not sure if that’s because it is relying on me setting the sounds through the player interface or not. This works as expected on Chrome.

The Page Visibility API is useful for detecting the visibility state of the page. We can listen to the visibilitychange event and then get the visibility state with document.visibilityState and so what we want with it.

An excerpt from Introducing the Page Visibility API

View original article

Subscribe to our Newsletter

Add your email address and receive an email every Friday covering off everything worth knowing about building your websites responsively.