DEV Community

Bryan Ollendyke
Bryan Ollendyke

Posted on

1 1

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

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay