Created
May 25, 2026 13:07
-
-
Save T1T4N/b84e421b5944bfc362d5e2ffa3ec475c to your computer and use it in GitHub Desktop.
TamperMonkey UserScript to stop video playback in background
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==UserScript== | |
| // @name Pause video in background | |
| // @namespace http://tampermonkey.net/ | |
| // @version 1.0 | |
| // @description Pause video when tab loses focus, resume when active | |
| // @match *://*/* | |
| // @grant none | |
| // ==/UserScript== | |
| (function () { | |
| 'use strict'; | |
| let lastPlayed = new WeakSet(); | |
| function pauseVideos() { | |
| document.querySelectorAll('video').forEach(video => { | |
| if (!video.paused && !video.ended) { | |
| lastPlayed.add(video); | |
| video.pause(); | |
| } | |
| }); | |
| } | |
| function resumeVideos() { | |
| document.querySelectorAll('video').forEach(video => { | |
| if (lastPlayed.has(video)) { | |
| video.play().catch(() => {}); | |
| lastPlayed.delete(video); | |
| } | |
| }); | |
| } | |
| document.addEventListener('visibilitychange', () => { | |
| if (document.hidden) pauseVideos(); | |
| else resumeVideos(); | |
| }); | |
| window.addEventListener('blur', pauseVideos); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment