DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Bryan Ollendyke
Bryan Ollendyke

Posted on

Auto pausing video with document.visibilityState

I recently was watching a video online when an advertisement was playing before the video that I couldn't skip. I recall my solution with fondness

aha! I'll show that advertiser. I'll just open a new tab for the next 30 seconds that are critical I do something!

To my surprise, the video would stop playing when I switched tabs. As a result of my lost 30 seconds, I created an issue to do the same in our own video-player web component.

It was really easy to add thanks in part to:

  • LitElement's firstUpdated life-cycle that made me aware of when the video-player was attached to the DOM
  • the visibilitychange event that fires on the document when changing tabs or minimizing the browsing window.

Here's the example Mozilla provides that I basically reverse engineered:

document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === 'visible') {
    backgroundMusic.play();
  } else {
    backgroundMusic.pause();
  }
});
Enter fullscreen mode Exit fullscreen mode

Switch out "music" for "toggle video" and this was a very easy thing to account for. Here's the code being walked through in this video. In the video I also demonstrate some ways to defeat the current implementation.

Video

Top comments (0)

Why You Need to Study Javascript Fundamentals

The harsh reality for JS Developers: If you don't study the fundamentals, you'll be just another β€œCoder”. Top learnings on how to get to the mid/senior level faster as a JavaScript developer by Dragos Nedelcu.