Skip to content

Instantly share code, notes, and snippets.

@w3collective
Created October 19, 2021 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w3collective/ef78d45d3d02c5754d98b54d77f8ab9c to your computer and use it in GitHub Desktop.
Save w3collective/ef78d45d3d02c5754d98b54d77f8ab9c to your computer and use it in GitHub Desktop.
Detect idle or active browser tabs with the Page Visibility API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Page Visibility API</title>
</head>
<body>
<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>
<script>
const toggleVideoPlayback = () => {
const video = document.getElementById("video");
return document.hidden ? video.pause() : video.play();
};
document.addEventListener("visibilitychange", toggleVideoPlayback);
</script>
</body>
</html>
@w3collective
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment