YouTube Usability

Disable frequently mistyped shortcuts (e.g. 0-9 number keys) and auto-looping on shorts.

当前为 2024-04-13 提交的版本,查看 最新版本

// ==UserScript==
// @name YouTube Usability
// @description Disable frequently mistyped shortcuts (e.g. 0-9 number keys) and auto-looping on shorts.
// @license MIT
// @icon https://m.youtube.com/static/apple-touch-icon-114x114-precomposed.png
// @namespace michaelsande.rs
// @version 2024.04.12
// @match https://www.youtube.com/*
// @match https://m.youtube.com/*
// @run-at document-start
// ==/UserScript==

// Tested on Greasemonkey and Violentmonkey for Firefox, and Userscripts for Safari.
(() => {
  "use strict";
  const beforeLoad = () => {
    const ALLOWED_MODIFIER_KEYS = ["Alt", "Control", "Meta", "OS"];
    const DISABLED_KEYS = new Set(
      "0123456789kjl".split("").concat(["Home", "End"])
    );

    window.addEventListener(
      "keydown",
      event => {
        if (
          DISABLED_KEYS.has(event.key) &&
          !ALLOWED_MODIFIER_KEYS.some(event.getModifierState.bind(event)) &&
          !event.isComposing
        ) {
          event.stopImmediatePropagation();
        }
      },
      true
    );

    window.addEventListener("load", afterLoad);
  };

  const afterLoad = () => {
    const shortsPlayer = document.getElementById("shorts-player");
    if (shortsPlayer !== null) {
      const disableShortLooping = () => {
        shortsPlayer.querySelector("video")?.removeAttribute("loop");
      };

      disableShortLooping();

      // Shorts video element gets replaced by YouTube so can't be used as MutationObserver target.
      new MutationObserver(disableShortLooping).observe(shortsPlayer, {
        attributeFilter: ["loop"],
        childList: true,
        subtree: true,
      });
    }
  };

  beforeLoad();
})();