More YouTube Hotkeys

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).

当前为 2024-03-19 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name More YouTube Hotkeys
  3. // @namespace https://greasyfork.org/en/users/85671-jcunews
  4. // @version 1.2.55
  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: "Focus comment input box", func: a => eleClick('#simplebox-placeholder')},
  30. {key: "\\", mods: "", desc: "Focus live chat input box", func: (a, b) => (a = document.querySelector('#chatframe')) && (b = a.contentDocument.querySelector('div#input')) && (a.focus(), b.focus())},
  31. {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)},
  32. {key: "!", mods: "S", func: a => videoSeekTo(0.15)},
  33. {key: "@", mods: "S", func: a => videoSeekTo(0.25)},
  34. {key: "#", mods: "S", func: a => videoSeekTo(0.35)},
  35. {key: "$", mods: "S", func: a => videoSeekTo(0.45)},
  36. {key: "%", mods: "S", func: a => videoSeekTo(0.55)},
  37. {key: "^", mods: "S", func: a => videoSeekTo(0.65)},
  38. {key: "&", mods: "S", func: a => videoSeekTo(0.75)},
  39. {key: "*", mods: "S", func: a => videoSeekTo(0.85)},
  40. {key: "(", mods: "S", func: a => videoSeekTo(0.95)},
  41. {key: "J", mods: "A", func: a => videoSeekChapter(-1), desc: "Seek to previous chapter"},
  42. {key: "L", mods: "A", func: a => videoSeekChapter(1), desc: "Seek to next chapter"},
  43. {key: "C", mods: "S", desc: "Select preferred subtitle language", func: selectCaption},
  44. {key: "J", mods: "S", desc: "Rewind video by 30 seconds", func: a => videoSeekBy(-30)},
  45. {key: "L", mods: "S", desc: "Fast forward video by 30 seconds", func: a => videoSeekBy(30)},
  46. {key: "G", mods: "A", desc: "Decrease video quality", func: selectQuality},
  47. {key: "H", mods: "A", desc: "Increase video quality", func: selectQuality},
  48. {key: "Y", mods: "A", desc: "Set video quality to auto", func: selectQuality},
  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"]),#actions button[title="Save"]')},
  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 selectCaption(v, o, c, a) {
  176. if (
  177. (v = document.querySelector('.html5-video-player')) && (o = v.getPlayerResponse().captions) &&
  178. (o = o.playerCaptionsTracklistRenderer) && (o = o.captionTracks)
  179. ) {
  180. if ((c = v.getOption("captions", "track")) && c.vss_id) {
  181. if (c.vss_id === ("." + subtitleLanguageCode)) {
  182. a = o.find(ct => ct.vssId === ("a." + subtitleLanguageCode));
  183. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  184. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  185. }
  186. if (!a && (c.vss_id === ("a." + subtitleLanguageCode))) {
  187. 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.is_translateable && (c.vss_id[0] === ".") && (c.vss_id.substr(1) !== subtitleLanguageCode)) {
  191. a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  192. }
  193. }
  194. if (!a) {
  195. a = o.find(ct => ct.vssId === ("." + subtitleLanguageCode));
  196. if (!a) a = o.find(ct => ct.vssId === ("a." + subtitleLanguageCode));
  197. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  198. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  199. if (!a) {
  200. a = o.find(ct => ct.isTranslatable && (
  201. ((ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode)) ||
  202. ((ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode))
  203. ));
  204. }
  205. if (!a) return;
  206. }
  207. a = {languageCode: a.languageCode, vss_id: a.vssId};
  208. if (a.languageCode !== subtitleLanguageCode) {
  209. v.getPlayerResponse().captions.playerCaptionsTracklistRenderer.translationLanguages.some(l => {
  210. if (l.languageCode === subtitleLanguageCode) {
  211. a.translationLanguage = {languageCode: subtitleLanguageCode};
  212. a.translationLanguage.languageName = l.languageName.simpleText;
  213. return true;
  214. }
  215. });
  216. }
  217. if (!c.languageCode) v.toggleSubtitles();
  218. v.setOption("captions", "track", a);
  219. }
  220. }
  221.  
  222. function toggleChatChap(a) {
  223. if (!eleClick([
  224. '#chat-messages #close-button button',
  225. '#show-hide-button.ytd-live-chat-frame button',
  226. '#show-hide-button.ytd-live-chat-frame > ytd-toggle-button-renderer.ytd-live-chat-frame',
  227. 'ytd-engagement-panel-section-list-renderer:is([target-id="engagement-panel-macro-markers-auto-chapters"],[target-id="engagement-panel-macro-markers-description-chapters"])[visibility="ENGAGEMENT_PANEL_VISIBILITY_EXPANDED"] #visibility-button button',
  228. '.ytp-chapter-title'
  229. ]) && (a = document.querySelector('ytd-live-chat-frame:not([collapsed]) #chatframe'))) a.contentWindow.postMessage("myhujs_toggleChatChap")
  230. }
  231.  
  232. function toggleYtVideoControls(v) {
  233. if (v = document.querySelector('.html5-video-player')) {
  234. if (v.classList.contains("ytp-autohide-active")) {
  235. v.classList.remove("ytp-autohide-active")
  236. } else if (v.classList.contains("ytp-autohide")) {
  237. v.classList.remove("ytp-autohide")
  238. } else v.classList.add("ytp-autohide")
  239. }
  240. }
  241.  
  242. function navUser(tn, tp, a, b, d) {
  243. if ((new RegExp(`^/(channel|user)/[^/]+/${tp}$`)).test(location.pathname)) {
  244. Array.from(document.querySelectorAll('.paper-tab')).some(e => {
  245. if (e.textContent.trim() === tn) {
  246. e.parentNode.click();
  247. return true;
  248. }
  249. });
  250. } else if (
  251. (a = document.querySelector(':is(.ytd-video-secondary-info-renderer,ytd-watch-metadata) yt-formatted-string.ytd-channel-name')) &&
  252. (d = a.__data) && (d = d.text) && (d = d.runs) && (d = d[0]) && (d = d.navigationEndpoint)
  253. ) {
  254. if (b = document.querySelector(".yt-page-navigation-progress")) {
  255. b.style.transform = "scaleX(.5)";
  256. b.parentNode.hidden = false
  257. }
  258. fetch(d.commandMetadata.webCommandMetadata.url, {credentials: "omit"}).then(r => r.text().then((h, x, ep, e, t, m) => {
  259. if ((h = h.match(/var ytInitialData = (\{.*?\});/)) && (h = JSON.parse(h[1]).contents.twoColumnBrowseResultsRenderer.tabs)) {
  260. x = new RegExp(`^\\/[^\\/]+(?:\\/[^\\/]+)?\\/${tp}$`);
  261. if (h.some((v, i, b) => {
  262. if ((b = v.tabRenderer) && !b.content && x.test((b = b.endpoint).commandMetadata.webCommandMetadata.url)) {
  263. e = (ep = d).browseEndpoint;
  264. t = d.clickTrackingParams;
  265. m = d.commandMetadata;
  266. d.browseEndpoint = b.browseEndpoint;
  267. d.clickTrackingParams = b.clickTrackingParams;
  268. d.commandMetadata = b.commandMetadata;
  269. return true
  270. }
  271. })) {
  272. a.firstElementChild.click();
  273. setTimeout(() => {
  274. ep.browseEndpoint = e;
  275. ep.clickTrackingParams = t;
  276. ep.commandMetadata = m;
  277. }, 20)
  278. }
  279. }
  280. }))
  281. }
  282. }
  283.  
  284. function checkHotkeyPopup(a, b, c, d, e) {
  285. if ((a = document.querySelector("#sections.ytd-hotkey-dialog-content")) && !a.querySelector(".more-hotkeys")) {
  286. a.__shady_native_appendChild(b = (d = a.firstElementChild).__shady_native_cloneNode(false)).classList.add("more-hotkeys");
  287. a.__shady_native_appendChild(d.__shady_native_cloneNode(false));
  288. b.__shady_native_appendChild(d.__shady_native_firstElementChild.__shady_native_cloneNode(false)).textContent = "More Hotkeys";
  289. c = b.__shady_native_appendChild(d.__shady_native_lastElementChild.__shady_native_cloneNode(false));
  290. d = d.__shady_native_lastElementChild.firstElementChild;
  291. hotkeys.forEach((h, e, f) => {
  292. if (h.desc) {
  293. e = c.__shady_native_appendChild(d.__shady_native_cloneNode(true));
  294. e.__shady_native_firstElementChild.textContent = h.desc;
  295. if (!(f = h.keys)) {
  296. if (h.ctrl || h.alt) {
  297. f = (h.ctrl ? "CTRL+" : "") + (h.shift ? "SHIFT+" : "") + (h.alt ? "ALT+" : "") + h.key;
  298. } else if (h.shift) {
  299. f = h.key + " (" + (h.shift ? "SHIFT+" : "") + (h.shift ? baseKeys[h.key] || h.key.toLowerCase() : h.key) + ")";
  300. } else f = h.key.toLowerCase();
  301. }
  302. e.__shady_native_lastElementChild.textContent = f;
  303. }
  304. });
  305. } else if (--ch) setTimeout(checkHotkeyPopup, 100);
  306. }
  307.  
  308. function editable(e) {
  309. var r = false;
  310. while (e) {
  311. if (e.contentEditable === "true") return true;
  312. e = e.parentNode;
  313. }
  314. return r;
  315. }
  316.  
  317. if (top !== self) {
  318. addEventListener("message", ev => (ev.data === "myhujs_toggleChatChap") && toggleChatChap())
  319. }
  320.  
  321. hotkeys.forEach(h => {
  322. var a = h.mods.toUpperCase().split("");
  323. h.shift = a.includes("S");
  324. h.ctrl = a.includes("C");
  325. h.alt = a.includes("A");
  326. });
  327. addEventListener("keydown", (ev, a) => {
  328. if ((a = document.activeElement) && (editable(a) || (a.tagName === "INPUT") || (a.tagName === "TEXTAREA"))) return;
  329. if ((ev.key === "?") && ev.shiftKey && !ev.ctrlKey && !ev.altKey) {
  330. ch = 10;
  331. setTimeout(checkHotkeyPopup, 100);
  332. }
  333. hotkeys.forEach(h => {
  334. if ((ev.key.toUpperCase() === h.key) && (ev.shiftKey === h.shift) && (ev.ctrlKey === h.ctrl) && (ev.altKey === h.alt)) {
  335. ev.preventDefault();
  336. ("function" === typeof h.func) && h.func(h);
  337. }
  338. });
  339. }, true);
  340.  
  341. })();