Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Created May 25, 2026 13:07
Show Gist options
  • Select an option

  • Save T1T4N/b84e421b5944bfc362d5e2ffa3ec475c to your computer and use it in GitHub Desktop.

Select an option

Save T1T4N/b84e421b5944bfc362d5e2ffa3ec475c to your computer and use it in GitHub Desktop.
TamperMonkey UserScript to stop video playback in background
// ==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