Pause/Mute HTML5 Audio/Video On Leaving Tab

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

当前为 2017-06-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Pause/Mute HTML5 Audio/Video On Leaving Tab
  3. // @namespace PauseMuteHTML5AudioVideoAudioOnLeavingTab
  4. // @description Pause or mute HTML5 audio/video on leaving a tab and restore them back on returning.
  5. // @version 1.0.1
  6. // @author jcunews
  7. // @include *://*/*
  8. // @grant none
  9. // q@run-at document-start
  10. // ==/UserScript==
  11.  
  12. //=== Configuration Start ===
  13. var muteInsteadOfPause = false; //set to `true` to mute instead of pause
  14. //=== Configuration End ===
  15.  
  16. var sHidden, sVisibilityChange, elements;
  17.  
  18. if ("undefined" !== typeof document.hidden) {
  19. sHidden = "hidden";
  20. sVisibilityChange = "visibilitychange";
  21. } else if ("undefined" !== typeof document.webkitHidden) {
  22. sHidden = "webkitHidden";
  23. sVisibilityChange = "webkitvisibilitychange";
  24. } else if ("undefined" !== typeof document.msHidden) {
  25. sHidden = "msHidden";
  26. sVisibilityChange = "msvisibilitychange";
  27. }
  28.  
  29. function checkStatus() {
  30. if (!document[sHidden]) {
  31. elements.forEach(function(v) {
  32. if (muteInsteadOfPause) {
  33. v.muted = false;
  34. } else v.play();
  35. });
  36. } else {
  37. elements = Array.prototype.slice.call(document.querySelectorAll("audio, video")).filter(
  38. function(v) {
  39. if (muteInsteadOfPause) {
  40. if (!v.muted) {
  41. v.muted = true;
  42. return true;
  43. }
  44. } else if (!v.paused) {
  45. v.pause();
  46. return true;
  47. }
  48. return false;
  49. }
  50. );
  51. }
  52. }
  53.  
  54. function init() {
  55. document.removeEventListener(sVisibilityChange, checkStatus);
  56. document.addEventListener(sVisibilityChange, checkStatus);
  57. }
  58.  
  59. init();
  60.  
  61. //Support for Structured Page Fragments. For e.g. YouTube
  62. addEventListener("spfdone", init);