pause-videos-when-not-visible

play/pause videos

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/492879/1362452/pause-videos-when-not-visible.js

  1. // ==UserScript==
  2. // @name Pause videos when not visible
  3. // @namespace https://greatest.deepsurf.us/users/821661
  4. // @version 1.0
  5. // @description play/pause videos
  6. // @author hdyzen
  7. // @match https://*/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11. 'use strict';
  12.  
  13. function observerIt(elements, threshold) {
  14. const observer = new MutationObserver(() => {
  15. const videos = document.querySelectorAll(elements);
  16. if (videos.length) {
  17. videos.forEach(video => {
  18. pauseVideo(video, threshold);
  19. });
  20. }
  21. });
  22.  
  23. observer.observe(document.body, {
  24. childList: true,
  25. subtree: true,
  26. });
  27. }
  28.  
  29. function pauseVideo(element, threshold) {
  30. const observer = new IntersectionObserver(
  31. entries => {
  32. entries.forEach(entry => {
  33. !entry.isIntersecting && !entry.target.paused ? entry.target.pause() : undefined;
  34. });
  35. },
  36. { threshold: threshold },
  37. );
  38.  
  39. observer.observe(element);
  40. }