Pause/Mute HTML5 Audio/Video On Leaving Tab

Pause or mute HTML5 audio/video on leaving a tab and restore them back on returning.

  1. // ==UserScript==
  2. // @name Pause/Mute HTML5 Audio/Video On Leaving Tab
  3. // @namespace PauseMuteHTML5AudioVideoAudioOnLeavingTab
  4. // @version 1.0.5
  5. // @license AGPL v3
  6. // @author jcunews
  7. // @description Pause or mute HTML5 audio/video on leaving a tab and restore them back on returning.
  8. // @website https://greasyfork.org/en/users/85671-jcunews
  9. // @include *://*/*
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (() => {
  14.  
  15. //=== Configuration Start ===
  16.  
  17. var muteInsteadOfPause = false; //set to `true` to mute instead of pause
  18.  
  19. //=== Configuration End ===
  20.  
  21. var sHidden, sVisibilityChange;
  22.  
  23. if ("undefined" !== typeof document.hidden) {
  24. sHidden = "hidden";
  25. sVisibilityChange = "visibilitychange";
  26. } else if ("undefined" !== typeof document.webkitHidden) {
  27. sHidden = "webkitHidden";
  28. sVisibilityChange = "webkitvisibilitychange";
  29. } else if ("undefined" !== typeof document.msHidden) {
  30. sHidden = "msHidden";
  31. sVisibilityChange = "msvisibilitychange";
  32. }
  33.  
  34. function checkStatus() {
  35. if (!document[sHidden]) {
  36. document.querySelectorAll("audio, video").forEach(function(v) {
  37. if (!v.off) return;
  38. if (muteInsteadOfPause) {
  39. v.muted = false;
  40. } else if (v.play_) {
  41. v.play = v.play_;
  42. delete v.play_;
  43. v.play();
  44. } else v.play();
  45. delete v.off;
  46. });
  47. } else {
  48. document.querySelectorAll("audio, video").forEach(
  49. function(v) {
  50. if (muteInsteadOfPause) {
  51. if (!v.muted) {
  52. v.off = true;
  53. setTimeout(() => v.muted = true, 0);
  54. }
  55. } else if (!v.paused) {
  56. v.off = true;
  57. setTimeout(() => {
  58. v.play_ = v.play;
  59. v.play = () => {};
  60. v.pause();
  61. }, 0);
  62. }
  63. }
  64. );
  65. }
  66. }
  67.  
  68. function init() {
  69. document.removeEventListener(sVisibilityChange, checkStatus);
  70. document.addEventListener(sVisibilityChange, checkStatus);
  71. }
  72.  
  73. //Support for Structured Page Fragments. For e.g. YouTube
  74. addEventListener("spfdone", init);
  75.  
  76. init();
  77. })();