Twitter unmute sound on autoplayed videos

Automatically unmutes the sound on autoplayed videos on Twitter.

  1. // ==UserScript==
  2. // @name Twitter unmute sound on autoplayed videos
  3. // @namespace http://zezombye.dev/
  4. // @version 0.1
  5. // @description Automatically unmutes the sound on autoplayed videos on Twitter.
  6. // @author Zezombye
  7. // @match https://twitter.com/*
  8. // @icon https://www.google.com/s2/favicons?sz=64&domain=twitter.com
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. /*
  13.  
  14. Twitter's code is so unnecessarily complex. I could just get the video element
  15. and do video.volume = 1 right? But nooo the twitter (sorry, X) engineers had
  16. to create the AudioElement within pure JS. So the only way I found to access it
  17. was to use the "m" hotkey to toggle mute. It isn't 100% reliable though. I
  18. couldn't manage to trigger the click event.
  19.  
  20. */
  21.  
  22. (function() {
  23. 'use strict';
  24.  
  25. setInterval(function() {
  26. let videos = document.getElementsByTagName("video");
  27. for (let video of videos) {
  28. if (video.hasAttribute("has-unmute-play-event")) {
  29. continue;
  30. }
  31. video.onplay = async function(e) {
  32. let videoKeyboardRegister = e.target.parentElement.parentElement.parentElement.children[1];
  33. if (videoKeyboardRegister.hasAttribute("has-been-played-once")) {
  34. return;
  35. }
  36. //console.log(videoKeyboardRegister);
  37. videoKeyboardRegister.setAttribute("has-been-played-once", "true");
  38. //videoKeyboardRegister.onkeypress = function(e) {console.log(e)};
  39. //Sometimes videos don't play if it's too low. Setting it to 50 is too low. So far on 100 no problem.
  40. await new Promise(r => setTimeout(r, 100));
  41. //console.log("owo");
  42. videoKeyboardRegister.focus({preventScroll: true});
  43. videoKeyboardRegister.dispatchEvent(new KeyboardEvent("keypress", {key: "m", charCode: 109, bubbles: false, cancelable: true, code: "Semicolon", isTrusted: true, keyCode: 109, which: 109}));
  44. }
  45. video.setAttribute("has-unmute-play-event", "true");
  46. }
  47. }, 100);
  48. })();