Set HTML5 media player volume

Script to set the volume of <video> and <audio> elements to reduced value (defaults to 50%), with a menu item to change for the current page.

  1. // ==UserScript==
  2. // @name Set HTML5 media player volume
  3. // @description Script to set the volume of <video> and <audio> elements to reduced value (defaults to 50%), with a menu item to change for the current page.
  4. // @namespace JeffersonScher
  5. // @author Jefferson "jscher2000" Scher
  6. // @copyright Copyright 2017 Jefferson Scher
  7. // @license BSD-3-clause
  8. // @include *
  9. // @version 0.6
  10. // @grant GM_registerMenuCommand
  11. // ==/UserScript==
  12.  
  13. var setvol_volumepct = 0.5; // Set volume to 50%
  14.  
  15. // == == == Detect added nodes / attach MutationObserver == == ==
  16. if (document.body){
  17. // Check existing videos
  18. setvol_checkNode(document.body);
  19. // Watch for changes that could be new videos
  20. var setvol_MutOb = (window.MutationObserver) ? window.MutationObserver : window.WebKitMutationObserver;
  21. if (setvol_MutOb){
  22. var setvol_chgMon = new setvol_MutOb(function(mutationSet){
  23. mutationSet.forEach(function(mutation){
  24. for (var setvol_node_count=0; setvol_node_count<mutation.addedNodes.length; setvol_node_count++){
  25. if (mutation.addedNodes[setvol_node_count].nodeType == 1){
  26. setvol_checkNode(mutation.addedNodes[setvol_node_count]);
  27. }
  28. }
  29. });
  30. });
  31. // attach setvol_chgMon to document.body
  32. var setvol_opts = {childList: true, subtree: true};
  33. setvol_chgMon.observe(document.body, setvol_opts);
  34. }
  35. }
  36.  
  37. function setvol_checkNode(el){
  38. if (el.nodeName == "video" || el.nodeName == "audio") var vids = [el];
  39. else var vids = el.querySelectorAll('video, audio');
  40. if (vids.length > 0){
  41. for (var j=0; j<vids.length; j++){
  42. vids[j].volume = setvol_volumepct;
  43. }
  44. }
  45. }
  46.  
  47. // This is not compatible with Greasemonkey 4, but should work in Tampermonkey and Violentmonkey
  48. function chgVol(e){
  49. var newvol = prompt('Enter value between 0.0 and 1.0 for 0% to 100%', setvol_volumepct);
  50. if (!isNaN(parseFloat(newvol))){
  51. var newnum = parseFloat(newvol);
  52. if (newnum < 0) newnum = 0;
  53. if (newnum > 1) newnum = 1;
  54. setvol_volumepct = newnum;
  55. setvol_checkNode(document.body);
  56. }
  57. }
  58. GM_registerMenuCommand('Change volume for this page', chgVol);