Advertisement
jcunews

more-youtube-hotkeys.user.js

Feb 17th, 2024
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name         More YouTube Hotkeys
  3. // @namespace    https://greasyfork.org/en/users/85671-jcunews
  4. // @version      1.2.51.1
  5. // @license      AGPLv3
  6. // @author       jcunews
  7. // @description  Adds more keyboard shortcuts for YouTube. The list of all new shortcuts is added into new "More Shortcuts" section on YouTube's "Keyboard shortcuts" popup which can be accessed via "?" or SHIFT+/ key (on U.S. keyboards).
  8. // @match        *://www.youtube.com/*
  9. // @grant        none
  10. // @run-at       document-start
  11. // ==/UserScript==
  12.  
  13. (ch => {
  14.  
  15.   //=== CONFIGURATION BEGIN
  16.   /*
  17.   `key` is the key name. If it's a letter, it must be in uppercase.
  18.   `mods` is a zero or up to 3 modifier key characters (in any order): `A`=Alt, `C`=Control, `S`=Shift. Character case is ignored.
  19.     e.g. "" (no modifier key), "s" (Shift), "Cs" (Control+Shift), "aSc" (Control+Shift+Alt).
  20.   `desc` is the hotkey description which will be added onto YouTube's Hotkey List Popup (accessible via `?` or `SHIFT+/` key).
  21.     If this property is empty or doesn't exist, the hotkey won't be included in YouTube's Hotkey List Popup.
  22.   `keys` is an optional custom text representation for the keyboard keys which is useful to represent multiple hotkeys.
  23.   `func` is the JavaScript function to execute with the activated hotkey object as the first argument.
  24.   */
  25.  
  26.   var hotkeys = [
  27.     {key: "`", mods: "", desc: "Toggle guide / sidebar", func: a => eleClick('#guide-button')},
  28.     {key: ";", mods: "", desc: "Focus channel search box", func: a => eleClick('#tabs-container :is(ytd-expandable-tab-renderer,.ytd-expandable-tab-renderer):has(form[action*="/search"]) button.yt-icon-button')},
  29.     {key: ")", mods: "S", desc: "Seek to specific point in the video (SHIFT+7 advances to 75% of duration)", keys: "SHIFT+0..SHIFT+9", func: a => videoSeekTo(0.05)},
  30.     {key: "!", mods: "S", func: a => videoSeekTo(0.15)},
  31.     {key: "@", mods: "S", func: a => videoSeekTo(0.25)},
  32.     {key: "#", mods: "S", func: a => videoSeekTo(0.35)},
  33.     {key: "$", mods: "S", func: a => videoSeekTo(0.45)},
  34.     {key: "%", mods: "S", func: a => videoSeekTo(0.55)},
  35.     {key: "^", mods: "S", func: a => videoSeekTo(0.65)},
  36.     {key: "&", mods: "S", func: a => videoSeekTo(0.75)},
  37.     {key: "*", mods: "S", func: a => videoSeekTo(0.85)},
  38.     {key: "(", mods: "S", func: a => videoSeekTo(0.95)},
  39.     {key: "J", mods: "A", func: a => videoSeekChapter(-1), desc: "Seek to previous chapter"},
  40.     {key: "L", mods: "A", func: a => videoSeekChapter(1), desc: "Seek to next chapter"},
  41.     {key: "C", mods: "S", desc: "Select preferred subtitle language", func: selectCaption},
  42.     {key: "J", mods: "S", desc: "Rewind video by 30 seconds", func: a => videoSeekBy(-30)},
  43.     {key: "L", mods: "S", desc: "Fast forward video by 30 seconds", func: a => videoSeekBy(30)},
  44.     {key: "G", mods: "A", desc: "Decrease video quality", func: selectQuality},
  45.     {key: "H", mods: "A", desc: "Increase video quality", func: selectQuality},
  46.     {key: "Y", mods: "A", desc: "Set video quality to auto", func: selectQuality},
  47.     {key: "-", mods: "", desc: "Decrease video playback speed by 0.25", func: a => adjustSpeed(-1)},
  48.     {key: "=", mods: "", desc: "Increase video playback speed by 0.25", func: a => adjustSpeed(1)},
  49.     {key: "E", mods: "", desc: "Toggle like video", func: a => eleClick(['#segmented-like-button button', ':is(#info, #description-and-actions, #actions) #menu ytd-toggle-button-renderer:nth-of-type(1) button#button', '#info #menu #top-level-buttons-computed ytd-toggle-button-renderer:nth-of-type(1) button#button', 'like-button-view-model button'])},
  50.     {key: "E", mods: "S", desc: "Toggle dislike video", func: a => eleClick(['#segmented-dislike-button button', ':is(#info, #description-and-actions, #actions) #menu ytd-toggle-button-renderer:nth-of-type(2) button#button', '#info #menu #top-level-buttons-computed ytd-toggle-button-renderer:nth-of-type(2) button#button', 'dislike-button-view-model button'])},
  51.     {key: "H", mods: "", desc: "Share video", func: a => eleClick([':is(#info, #description-and-actions) #menu ytd-button-renderer:nth-of-type(1) button#button,ytd-watch-metadata #menu ytd-button-renderer button:has(div[style*="share"])', 'ytd-watch-metadata #menu ytd-button-renderer button[aria-label="Share"]'])},
  52.     {key: "N", mods: "", desc: "Download video", func: a => eleClick(['ytd-watch-metadata #menu ytd-button-renderer button:has(div[style*="download"])', '.ytd-download-button-renderer button'])},
  53.     {key: "Q", mods: "S", desc: "Toggle YouTube video controls", func: toggleYtVideoControls},
  54.     {key: "V", mods: "", desc: "Save video into playlist", func: a => eleClick(':is(#info, #description-and-actions) #menu ytd-button-renderer:last-of-type button#button,#actions button:has(div[style*="list_add"])')},
  55.     {key: "U", mods: "", desc: "Toggle subscription", func: a => eleClick('#meta ytd-subscribe-button-renderer>.ytd-subscribe-button-renderer:not(div),paper-button.ytd-subscribe-button-renderer,tp-yt-paper-button.ytd-subscribe-button-renderer,ytd-subscribe-button-renderer.ytd-watch-metadata button', true)},
  56.     {key: "Y", mods: "", desc: "Toggle subscription notification", func: a => eleClick(['ytd-watch-flexy #meta  .ytd-subscription-notification-toggle-button-renderer>button#button', 'ytd-watch-flexy #notification-preference-toggle-button > .ytd-subscribe-button-renderer'])},
  57.     {key: "R", mods: "", desc: "Toggle replay chat or chapter list", func: toggleChatChap},
  58.     {key: "R", mods: "S", desc: "Toggle sponsored video list", func: a => eleClick('ytd-engagement-panel-section-list-renderer[target-id="ytbc-related-shelf"] #visibility-button .yt-icon-button')},
  59.     {key: "X", mods: "", desc: "Toggle autoplay of next non-playlist video", func: a => eleClick(['paper-toggle-button.ytd-compact-autoplay-renderer', 'button[data-tooltip-target-id="ytp-autonav-toggle-button"]'])},
  60.     {key: "V", mods: "S", desc: "Go to user/channel video page", func: a => navUser("Videos", "videos")},
  61.     {key: "Y", mods: "S", desc: "Go to user/channel playlists page", func: a => navUser("Playlists", "playlists")},
  62.     {key: "`", mods: "C", desc: "Go to YouTube home page", func: a => eleClick('a#logo')},
  63.     {key: "S", mods: "S", desc: 'Go to Subscriptions page', func: a => eleClick('a[href="/feed/subscriptions"]') || (location.href = "/feed/subscriptions")},
  64.     {key: "F", mods: "S", desc: 'Go to Feeds ("You") page', func: a => eleClick('a[href="/feed/you"]') || (location.href = "/feed/you")},
  65.     {key: "I", mods: "S", desc: "Go to History page", func: a => eleClick('a[href="/feed/history"]') || (location.href = "/feed/history")},
  66.     {key: "W", mods: "S", desc: "Go to Watch Later page", func: a => eleClick('a[href="/playlist?list=WL"]') || (location.href = "/playlist?list=WL")},
  67.     {key: "K", mods: "S", desc: "Go to Liked Videos page", func: a => eleClick('a[href="/playlist?list=LL"]') || (location.href = "/playlist?list=LL")},
  68.     {key: "T", mods: "S", desc: "Go to Account page", func: a => eleClick('a[href="/account"]') || (location.href = "/account")}
  69.   ];
  70.   var subtitleLanguageCode = "en"; //2-letters language code for select preferred subtitle language hotkey
  71.  
  72.   //=== CONFIGURATION END
  73.  
  74.   var baseKeys = {};
  75.   ("~`!1@2#3$4%5^6&7*8(9)0_-+={[}]:;\"'|\\<,>.?/").split("").forEach((c, i, a) => {
  76.     if ((i & 1) === 0) baseKeys[c] = a[i + 1];
  77.   });
  78.  
  79.   function isHidden(e) {
  80.     while (e && e.style) {
  81.       if (getComputedStyle(e).display === "none") {
  82.         return true;
  83.       }
  84.       e = e.parentNode
  85.     }
  86.     return false
  87.   }
  88.  
  89.   function eleClick(s, l, e) {
  90.     if (s.some) {
  91.       s.some(a => {
  92.         if (e = document.querySelector(a)) {
  93.           if (e.disabled || isHidden(e)) e = null
  94.         }
  95.         if (e) return true
  96.       });
  97.     } else if (l) {
  98.       e = Array.from(document.querySelectorAll(s)).find(f => !f.disabled && !isHidden(f))
  99.     } else if (e = document.querySelector(s)) {
  100.       if (e.disabled || isHidden(e)) e = null
  101.     }
  102.     if (e) {
  103.       e.click();
  104.       return true
  105.     }
  106.   }
  107.  
  108.   function videoSeekBy(t, v) {
  109.     (v = document.querySelector('.html5-video-player')) && v.seekBy(t);
  110.   }
  111.  
  112.   function videoSeekTo(p, v) {
  113.     (v = document.querySelector('.html5-video-player')) && v.seekTo(v.getDuration() * p);
  114.   }
  115.  
  116.   function videoSeekChapter(d, v, s, t) {
  117.     if (
  118.       (v = document.querySelector('.html5-video-player')) && (s = v.getPlayerResponse().videoDetails) &&
  119.       (s = s.shortDescription)
  120.     ) {
  121.       t = v.getCurrentTime();
  122.       if (s = s.match(/^(?:\s*\d+\.)?\s*(\d{1,2}:)?\d{1,2}:\d{1,2}\s+\S+.*/gm)) {
  123.         s = s.map(s => {
  124.           s = s.match(/^(?:\s*\d+\.)?\s*(\d{1,2}:)?(\d{1,2}):(\d{1,2})/);
  125.           s[1] = s[1] ? parseInt(s[1]) : 0;
  126.           s[2] = s[2] ? parseInt(s[2]) : 0;
  127.           s[3] = s[3] ? parseInt(s[3]) : 0;
  128.           return (s[1] * 3600) + (s[2] * 60) + s[3]
  129.         })
  130.       }
  131.     }
  132.     if (
  133.       (!s || !s.some || !s.length) && (s = window["page-manager"]) && (s = s.getCurrentData()) && (s = s.response) && (s = s.playerOverlays) &&
  134.       (s = s.playerOverlayRenderer) && (s = s.decoratedPlayerBarRenderer) && (s = s.decoratedPlayerBarRenderer) && (s = s.playerBar) &&
  135.       (s = s.multiMarkersPlayerBarRenderer) && (s = s.markersMap)
  136.     ) {
  137.       s.some(m => {
  138.         if (m.key === "AUTO_CHAPTERS") {
  139.           if ((m = m.value) && (m = m.chapters) && m.length && m[0] && m[0].chapterRenderer && m[0].chapterRenderer) {
  140.             s = m.map(a => Math.floor(a.chapterRenderer.timeRangeStartMillis / 1000))
  141.           }
  142.           return true
  143.         }
  144.       })
  145.     }
  146.     if (s && s.some) {
  147.       if (s.length && (s[0] > 1)) s.unshift(0);
  148.       s.some((c, i) => {
  149.         if ((d < 0) && (c <= t) && (!s[i + 1] || (s[i + 1] > t))) {
  150.           if ((c + 1) >= t) {
  151.             v.seekTo(s[i - 1]);
  152.           } else v.seekTo(c);
  153.           return true
  154.         } else if ((d > 0) && (c > t) && i) {
  155.           v.seekTo(c);
  156.           return true
  157.         }
  158.       })
  159.     }
  160.   }
  161.  
  162.   function selectQuality(i, v, e, c) {
  163.     if ((v = document.querySelector('.html5-video-player')) && (v.getAvailableQualityLabels().length > 1)) {
  164.       if (i.key === "Y") {
  165.         v.setPlaybackQualityRange("auto", "auto");
  166.       } else {
  167.         (e = v.getAvailableQualityLevels()).pop();
  168.         c = e.indexOf(v.getPlaybackQuality());
  169.         i = i.key === "G" ? 1 : -1;
  170.         if (e = e[c + i]) v.setPlaybackQualityRange(e, e);
  171.       }
  172.     }
  173.   }
  174.  
  175.   function adjustSpeed(d, s) {
  176.     if (s = Math.floor((movie_player.getPlaybackRate() * 4) + d) / 4) movie_player.setPlaybackRate(s)
  177.   }
  178.  
  179.   function selectCaption(v, o, c, a) {
  180.     if (
  181.       (v = document.querySelector('.html5-video-player')) && (o = v.getPlayerResponse().captions) &&
  182.       (o = o.playerCaptionsTracklistRenderer) && (o = o.captionTracks)
  183.     ) {
  184.       if ((c = v.getOption("captions", "track")) && c.vss_id) {
  185.         if (c.vss_id === ("." + subtitleLanguageCode)) {
  186.           a = o.find(ct => ct.vssId === ("a." + subtitleLanguageCode));
  187.           if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  188.           if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  189.         }
  190.         if (!a && (c.vss_id === ("a." + subtitleLanguageCode))) {
  191.           a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  192.           if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  193.         }
  194.         if (!a && c.is_translateable && (c.vss_id[0] === ".") && (c.vss_id.substr(1) !== subtitleLanguageCode)) {
  195.           a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  196.         }
  197.       }
  198.       if (!a) {
  199.         a = o.find(ct => ct.vssId === ("." + subtitleLanguageCode));
  200.         if (!a) a = o.find(ct => ct.vssId === ("a." + subtitleLanguageCode));
  201.         if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  202.         if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  203.         if (!a) {
  204.           a = o.find(ct => ct.isTranslatable && (
  205.             ((ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode)) ||
  206.             ((ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode))
  207.           ));
  208.         }
  209.         if (!a) return;
  210.       }
  211.       a = {languageCode: a.languageCode, vss_id: a.vssId};
  212.       if (a.languageCode !== subtitleLanguageCode) {
  213.         v.getPlayerResponse().captions.playerCaptionsTracklistRenderer.translationLanguages.some(l => {
  214.           if (l.languageCode === subtitleLanguageCode) {
  215.             a.translationLanguage = {languageCode: subtitleLanguageCode};
  216.             a.translationLanguage.languageName = l.languageName.simpleText;
  217.             return true;
  218.           }
  219.         });
  220.       }
  221.       if (!c.languageCode) v.toggleSubtitles();
  222.       v.setOption("captions", "track", a);
  223.     }
  224.   }
  225.  
  226.   function toggleChatChap(a) {
  227.     if (!eleClick([
  228.       '#chat-messages #close-button button',
  229.       '#show-hide-button.ytd-live-chat-frame button',
  230.       '#show-hide-button.ytd-live-chat-frame > ytd-toggle-button-renderer.ytd-live-chat-frame',
  231.       'ytd-engagement-panel-section-list-renderer[target-id="engagement-panel-macro-markers-description-chapters"][visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"] #visibility-button button',
  232.       '.ytp-chapter-title'
  233.     ]) && (a = document.querySelector('ytd-live-chat-frame:not([collapsed]) #chatframe'))) a.contentWindow.postMessage("myhujs_toggleChatChap")
  234.   }
  235.  
  236.   function toggleYtVideoControls(v) {
  237.     if (v = document.querySelector('.html5-video-player')) {
  238.       if (v.classList.contains("ytp-autohide-active")) {
  239.         v.classList.remove("ytp-autohide-active")
  240.       } else if (v.classList.contains("ytp-autohide")) {
  241.         v.classList.remove("ytp-autohide")
  242.       } else v.classList.add("ytp-autohide")
  243.     }
  244.   }
  245.  
  246.   function navUser(tn, tp, a, b, d) {
  247.     if ((new RegExp(`^/(channel|user)/[^/]+/${tp}$`)).test(location.pathname)) {
  248.       Array.from(document.querySelectorAll('.paper-tab')).some(e => {
  249.         if (e.textContent.trim() === tn) {
  250.           e.parentNode.click();
  251.           return true;
  252.         }
  253.       });
  254.     } else if (
  255.       (a = document.querySelector(':is(.ytd-video-secondary-info-renderer,ytd-watch-metadata) yt-formatted-string.ytd-channel-name')) &&
  256.       (d = a.__data) && (d = d.text) && (d = d.runs) && (d = d[0]) && (d = d.navigationEndpoint)
  257.     ) {
  258.       if (b = document.querySelector(".yt-page-navigation-progress")) {
  259.         b.style.transform = "scaleX(.5)";
  260.         b.parentNode.hidden = false
  261.       }
  262.       fetch(d.commandMetadata.webCommandMetadata.url, {credentials: "omit"}).then(r => r.text().then((h, x, ep, e, t, m) => {
  263.         if ((h = h.match(/var ytInitialData = (\{.*?\});/)) && (h = JSON.parse(h[1]).contents.twoColumnBrowseResultsRenderer.tabs)) {
  264.           x = new RegExp(`^\\/[^\\/]+(?:\\/[^\\/]+)?\\/${tp}$`);
  265.           if (h.some((v, i, b) => {
  266.             if ((b = v.tabRenderer) && !b.content && x.test((b = b.endpoint).commandMetadata.webCommandMetadata.url)) {
  267.               e = (ep = d).browseEndpoint;
  268.               t = d.clickTrackingParams;
  269.               m = d.commandMetadata;
  270.               d.browseEndpoint = b.browseEndpoint;
  271.               d.clickTrackingParams = b.clickTrackingParams;
  272.               d.commandMetadata = b.commandMetadata;
  273.               return true
  274.             }
  275.           })) {
  276.             a.firstElementChild.click();
  277.             setTimeout(() => {
  278.               ep.browseEndpoint = e;
  279.               ep.clickTrackingParams = t;
  280.               ep.commandMetadata = m;
  281.             }, 20)
  282.           }
  283.         }
  284.       }))
  285.     }
  286.   }
  287.  
  288.   function checkHotkeyPopup(a, b, c, d, e) {
  289.     if ((a = document.querySelector("#sections.ytd-hotkey-dialog-content")) && !a.querySelector(".more-hotkeys")) {
  290.       a.__shady_native_appendChild(b = (d = a.firstElementChild).__shady_native_cloneNode(false)).classList.add("more-hotkeys");
  291.       a.__shady_native_appendChild(d.__shady_native_cloneNode(false));
  292.       b.__shady_native_appendChild(d.__shady_native_firstElementChild.__shady_native_cloneNode(false)).textContent = "More Hotkeys";
  293.       c = b.__shady_native_appendChild(d.__shady_native_lastElementChild.__shady_native_cloneNode(false));
  294.       d = d.__shady_native_lastElementChild.firstElementChild;
  295.       hotkeys.forEach((h, e, f) => {
  296.         if (h.desc) {
  297.           e = c.__shady_native_appendChild(d.__shady_native_cloneNode(true));
  298.           e.__shady_native_firstElementChild.textContent = h.desc;
  299.           if (!(f = h.keys)) {
  300.             if (h.ctrl || h.alt) {
  301.               f = (h.ctrl ? "CTRL+" : "") + (h.shift ? "SHIFT+" : "") + (h.alt ? "ALT+" : "") + h.key;
  302.             } else if (h.shift) {
  303.               f = h.key + " (" + (h.shift ? "SHIFT+" : "") + (h.shift ? baseKeys[h.key] || h.key.toLowerCase() : h.key) + ")";
  304.             } else f = h.key.toLowerCase();
  305.           }
  306.           e.__shady_native_lastElementChild.textContent = f;
  307.         }
  308.       });
  309.     } else if (--ch) setTimeout(checkHotkeyPopup, 100);
  310.   }
  311.  
  312.   function editable(e) {
  313.     var r = false;
  314.     while (e) {
  315.       if (e.contentEditable === "true") return true;
  316.       e = e.parentNode;
  317.     }
  318.     return r;
  319.   }
  320.  
  321.   if (top !== self) {
  322.     addEventListener("message", ev => (ev.data === "myhujs_toggleChatChap") && toggleChatChap())
  323.   }
  324.  
  325.   hotkeys.forEach(h => {
  326.     var a = h.mods.toUpperCase().split("");
  327.     h.shift = a.includes("S");
  328.     h.ctrl = a.includes("C");
  329.     h.alt = a.includes("A");
  330.   });
  331.   addEventListener("keydown", (ev, a) => {
  332.     if ((a = document.activeElement) && (editable(a) || (a.tagName === "INPUT") || (a.tagName === "TEXTAREA"))) return;
  333.     if ((ev.key === "?") && ev.shiftKey && !ev.ctrlKey && !ev.altKey) {
  334.       ch = 10;
  335.       setTimeout(checkHotkeyPopup, 100);
  336.     }
  337.     hotkeys.forEach(h => {
  338.       if ((ev.key.toUpperCase() === h.key) && (ev.shiftKey === h.shift) && (ev.ctrlKey === h.ctrl) && (ev.altKey === h.alt)) {
  339.         ev.preventDefault();
  340.         ("function" === typeof h.func) && h.func(h);
  341.       }
  342.     });
  343.   }, true);
  344.  
  345. })();
  346.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement