Greasy Fork is available in English.

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

  1. // ==UserScript==
  2. // @name More YouTube Hotkeys
  3. // @namespace https://greasyfork.org/en/users/85671-jcunews
  4. // @version 1.3.62
  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 => focusChatFrame('div#input')},
  31. {key: "\\",mods: "A", desc: "Focus live chat message list", func: a => focusChatFrame('#item-scroller')},
  32. {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)},
  33. {key: "!", mods: "S", func: a => videoSeekTo(0.15)},
  34. {key: "@", mods: "S", func: a => videoSeekTo(0.25)},
  35. {key: "#", mods: "S", func: a => videoSeekTo(0.35)},
  36. {key: "$", mods: "S", func: a => videoSeekTo(0.45)},
  37. {key: "%", mods: "S", func: a => videoSeekTo(0.55)},
  38. {key: "^", mods: "S", func: a => videoSeekTo(0.65)},
  39. {key: "&", mods: "S", func: a => videoSeekTo(0.75)},
  40. {key: "*", mods: "S", func: a => videoSeekTo(0.85)},
  41. {key: "(", mods: "S", func: a => videoSeekTo(0.95)},
  42. {key: "J", mods: "A", desc: "Seek to previous chapter", func: a => videoSeekChapter(-1)},
  43. {key: "L", mods: "A", desc: "Seek to next chapter", func: a => videoSeekChapter(1)},
  44. {key: "C", mods: "S", desc: "Select preferred subtitle language", func: selectCaption},
  45. {key: "J", mods: "S", desc: "Rewind video by 30 seconds", func: a => videoSeekBy(-30)},
  46. {key: "L", mods: "S", desc: "Fast forward video by 30 seconds", func: a => videoSeekBy(30)},
  47. {key: "G", mods: "A", desc: "Decrease video quality", func: selectQuality},
  48. {key: "H", mods: "A", desc: "Increase video quality", func: selectQuality},
  49. {key: "Y", mods: "A", desc: "Set video quality to auto", func: selectQuality},
  50. {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'])},
  51. {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'])},
  52. {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 :is(ytd-button-renderer,yt-button-view-model) button:has(div[style*="share"])', 'ytd-watch-metadata #menu :is(ytd-button-renderer,yt-button-view-model) button[aria-label="Share"]'])},
  53. {key: "N", mods: "", desc: "Download video", func: a => doBtnOrMenu(['ytd-watch-metadata #menu ytd-button-renderer button:has(div[style*="download"])', '.ytd-download-button-renderer button'], '', 'primaryIconType', "OFFLINE_DOWNLOAD")},
  54. {key: "Q", mods: "S", desc: "Toggle YouTube video controls", func: toggleYtVideoControls},
  55. {key: "V", mods: "", desc: "Save video into playlist", func: a => doBtnOrMenu(':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"]', 'PLAYLIST_ADD')},
  56. {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)},
  57. {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'])},
  58. {key: "R", mods: "", desc: "Toggle replay chat or chapter list", func: toggleChatChap},
  59. {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')},
  60. {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"]'])},
  61. {key: "V", mods: "S", desc: "Go to user/channel video page", func: a => navUser("Videos", "videos")},
  62. {key: "Y", mods: "S", desc: "Go to user/channel playlists page", func: a => navUser("Playlists", "playlists")},
  63. {key: "`", mods: "C", desc: "Go to YouTube home page", func: a => eleClick('a#logo')},
  64. {key: "S", mods: "S", desc: 'Go to Subscriptions page', func: a => eleClick('a[href="/feed/subscriptions"]') || (location.href = "/feed/subscriptions")},
  65. {key: "F", mods: "S", desc: 'Go to Feeds ("You") page', func: a => eleClick('a[href="/feed/you"]') || (location.href = "/feed/you")},
  66. {key: "I", mods: "S", desc: "Go to History page", func: a => eleClick('a[href="/feed/history"]') || (location.href = "/feed/history")},
  67. {key: "W", mods: "S", desc: "Go to Watch Later page", func: a => eleClick('a[href="/playlist?list=WL"]') || (location.href = "/playlist?list=WL")},
  68. {key: "K", mods: "S", desc: "Go to Liked Videos page", func: a => eleClick('a[href="/playlist?list=LL"]') || (location.href = "/playlist?list=LL")},
  69. {key: "T", mods: "S", desc: "Go to Account page", func: a => eleClick('a[href="/account"]') || (location.href = "/account")}
  70. ];
  71. var subtitleLanguageCode = "en"; //2-letters language code for select preferred subtitle language hotkey
  72.  
  73. //=== CONFIGURATION END
  74.  
  75. var baseKeys = {};
  76. ("~`!1@2#3$4%5^6&7*8(9)0_-+={[}]:;\"'|\\<,>.?/").split("").forEach((c, i, a) => {
  77. if ((i & 1) === 0) baseKeys[c] = a[i + 1];
  78. });
  79.  
  80. function isHidden(e) {
  81. while (e && e.style) {
  82. if (e.hidden || (getComputedStyle(e).display === "none")) {
  83. return true;
  84. }
  85. e = e.parentNode
  86. }
  87. return false
  88. }
  89.  
  90. function eleClick(s, l, e) {
  91. if (s.some) {
  92. s.some(a => {
  93. if (e = document.querySelector(a)) {
  94. if (e.disabled || isHidden(e)) e = null
  95. }
  96. if (e) return true
  97. });
  98. } else if (l) {
  99. e = Array.from(document.querySelectorAll(s)).find(f => !f.disabled && !isHidden(f))
  100. } else if (e = document.querySelector(s)) {
  101. if (e.disabled || isHidden(e)) e = null
  102. }
  103. if (e) {
  104. e.click();
  105. return true
  106. }
  107. }
  108.  
  109. function doBtnOrMenu(btnSel, menuIcon, propName, propVal, itms, elePopup, z) {
  110. if (
  111. eleClick(btnSel) || !(btnSel = document.querySelector('#actions ytd-menu-renderer #button-shape button')) || isHidden(btnSel)
  112. ) return;
  113. (elePopup = document.querySelector('ytd-popup-container')).style.display = "none";
  114. try {
  115. btnSel.click();
  116. setTimeout(() => {
  117. ((itms = elePopup?.querySelector('#items'))?.__dataHost?.__data?.data || itms?.__data)?.items?.some?.((itm, i) => {
  118. if (propName) {
  119. if (propName in itm) {
  120. if ((propVal === undefined) || (itm[propName] === propVal)) itms.children[i].firstElementChild.click()
  121. return true
  122. }
  123. } else if ((itm.menuServiceItemRenderer || itm.polymerController?.data)?.icon?.iconType === menuIcon) {
  124. itms.children[i].firstElementChild.click()
  125. return true
  126. }
  127. });
  128. elePopup.style.display = ""
  129. }, 0)
  130. } catch(z) {
  131. elePopup.style.display = ""
  132. }
  133. }
  134.  
  135. function videoSeekBy(t, v) {
  136. (v = document.querySelector('.html5-video-player')) && v.seekBy(t);
  137. }
  138.  
  139. function videoSeekTo(p, v) {
  140. (v = document.querySelector('.html5-video-player')) && v.seekTo(v.getDuration() * p);
  141. }
  142.  
  143. function videoSeekChapter(d, v, s, t) {
  144. if (
  145. (v = document.querySelector('.html5-video-player')) && (s = v.getPlayerResponse().videoDetails) &&
  146. (s = s.shortDescription)
  147. ) {
  148. t = v.getCurrentTime();
  149. if (s = s.match(/^(?:\s*\d+\.)?\s*(\d{1,2}:)?\d{1,2}:\d{1,2}\s+\S+.*/gm)) {
  150. s = s.map(s => {
  151. s = s.match(/^(?:\s*\d+\.)?\s*(\d{1,2}:)?(\d{1,2}):(\d{1,2})/);
  152. s[1] = s[1] ? parseInt(s[1]) : 0;
  153. s[2] = s[2] ? parseInt(s[2]) : 0;
  154. s[3] = s[3] ? parseInt(s[3]) : 0;
  155. return (s[1] * 3600) + (s[2] * 60) + s[3]
  156. })
  157. }
  158. }
  159. if (
  160. (!s || !s.some || !s.length) && (s = window["page-manager"]) && (s = s.getCurrentData()) && (s = s.response) && (s = s.playerOverlays) &&
  161. (s = s.playerOverlayRenderer) && (s = s.decoratedPlayerBarRenderer) && (s = s.decoratedPlayerBarRenderer) && (s = s.playerBar) &&
  162. (s = s.multiMarkersPlayerBarRenderer) && (s = s.markersMap)
  163. ) {
  164. s.some(m => {
  165. if (/^(AUTO|DESCRIPTION)_CHAPTERS$/.test(m.key)) {
  166. if ((m = m.value) && (m = m.chapters) && m.length && m[0] && m[0].chapterRenderer && m[0].chapterRenderer) {
  167. s = m.map(a => Math.floor(a.chapterRenderer.timeRangeStartMillis / 1000))
  168. }
  169. return true
  170. }
  171. })
  172. }
  173. if (s && s.some) {
  174. if (s.length && (s[0] > 1)) s.unshift(0);
  175. s.some((c, i) => {
  176. if ((d < 0) && (c <= t) && (!s[i + 1] || (s[i + 1] > t))) {
  177. if ((c + 1) >= t) {
  178. v.seekTo(s[i - 1]);
  179. } else v.seekTo(c);
  180. return true
  181. } else if ((d > 0) && (c > t) && i) {
  182. v.seekTo(c);
  183. return true
  184. }
  185. })
  186. }
  187. }
  188.  
  189. function selectQuality(i, v, e, c) {
  190. if ((v = document.querySelector('.html5-video-player')) && (v.getAvailableQualityLabels().length > 1)) {
  191. if (i.key === "Y") {
  192. v.setPlaybackQualityRange("auto", "auto");
  193. } else {
  194. (e = v.getAvailableQualityLevels()).pop();
  195. c = e.indexOf(v.getPlaybackQuality());
  196. i = i.key === "G" ? 1 : -1;
  197. if (e = e[c + i]) v.setPlaybackQualityRange(e, e);
  198. }
  199. }
  200. }
  201.  
  202. function selectCaption(v, o, c, a) {
  203. if (
  204. (v = document.querySelector('.html5-video-player')) && (o = v.getPlayerResponse().captions) &&
  205. (o = o.playerCaptionsTracklistRenderer) && (o = o.captionTracks)
  206. ) {
  207. if ((c = v.getOption("captions", "track")) && c.vss_id) {
  208. if (c.vss_id === ("." + subtitleLanguageCode)) {
  209. a = o.find(ct => ct.vssId === ("a." + subtitleLanguageCode));
  210. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  211. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  212. }
  213. if (!a && (c.vss_id === ("a." + subtitleLanguageCode))) {
  214. a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  215. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  216. }
  217. if (!a && c.is_translateable && (c.vss_id[0] === ".") && (c.vss_id.substr(1) !== subtitleLanguageCode)) {
  218. a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  219. }
  220. }
  221. if (!a) {
  222. a = o.find(ct => ct.vssId === ("." + subtitleLanguageCode));
  223. if (!a) a = o.find(ct => ct.vssId === ("a." + subtitleLanguageCode));
  224. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode));
  225. if (!a) a = o.find(ct => ct.isTranslatable && (ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode));
  226. if (!a) {
  227. a = o.find(ct => ct.isTranslatable && (
  228. ((ct.vssId[0] === ".") && (ct.vssId.substr(1) !== subtitleLanguageCode)) ||
  229. ((ct.vssId[1] === ".") && (ct.vssId.substr(2) !== subtitleLanguageCode))
  230. ));
  231. }
  232. if (!a) return;
  233. }
  234. a = {languageCode: a.languageCode, vss_id: a.vssId};
  235. if (a.languageCode !== subtitleLanguageCode) {
  236. v.getPlayerResponse().captions.playerCaptionsTracklistRenderer.translationLanguages.some(l => {
  237. if (l.languageCode === subtitleLanguageCode) {
  238. a.translationLanguage = {languageCode: subtitleLanguageCode};
  239. a.translationLanguage.languageName = l.languageName.simpleText;
  240. return true;
  241. }
  242. });
  243. }
  244. if (!c.languageCode) v.toggleSubtitles();
  245. v.setOption("captions", "track", a);
  246. }
  247. }
  248.  
  249. function toggleChatChap(a) {
  250. if (!eleClick([
  251. '#chat-messages #close-button button',
  252. '#show-hide-button.ytd-live-chat-frame button',
  253. '#show-hide-button.ytd-live-chat-frame > ytd-toggle-button-renderer.ytd-live-chat-frame',
  254. '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',
  255. '.ytp-chapter-title'
  256. ]) && (a = document.querySelector('ytd-live-chat-frame:not([collapsed]) #chatframe'))) a.contentWindow.postMessage("myhujs_toggleChatChap")
  257. }
  258.  
  259. function focusChatFrame(sel, a, b) {
  260. (a = document.querySelector('#chatframe')) && (b = a.contentDocument.querySelector(sel)) && (a.focus(), b.focus())
  261. }
  262.  
  263. function toggleYtVideoControls(v) {
  264. if (v = document.querySelector('.html5-video-player')) {
  265. if (v.classList.contains("ytp-autohide-active")) {
  266. v.classList.remove("ytp-autohide-active")
  267. } else if (v.classList.contains("ytp-autohide")) {
  268. v.classList.remove("ytp-autohide")
  269. } else v.classList.add("ytp-autohide")
  270. }
  271. }
  272.  
  273. function navUser(tn, tp, a, b, d) {
  274. if ((new RegExp(`^/(channel|user)/[^/]+/${tp}$`)).test(location.pathname)) {
  275. Array.from(document.querySelectorAll('.paper-tab')).some(e => {
  276. if (e.textContent.trim() === tn) {
  277. e.parentNode.click();
  278. return true;
  279. }
  280. });
  281. } else if (
  282. (a = document.querySelector(':is(.ytd-video-secondary-info-renderer,ytd-watch-metadata) yt-formatted-string.ytd-channel-name')) &&
  283. (
  284. ((d = a.__data) && (d = d.text) && (d = d.runs) && (d = d[0]) && (d = d.navigationEndpoint)) ||
  285. ((d = a.__dataHost) && (d = d.__data) && (d = d.channelName) && (d = d.runs) && (d = d[0]) && (d = d.navigationEndpoint))
  286. )
  287. ) {
  288. if (b = document.querySelector(".yt-page-navigation-progress")) {
  289. b.style.transform = "scaleX(.5)";
  290. b.parentNode.hidden = false
  291. }
  292. fetch(d.commandMetadata.webCommandMetadata.url, {credentials: "omit"}).then(r => r.text().then((h, x, ep, e, t, m) => {
  293. if ((h = h.match(/var ytInitialData = (\{.*?\});/)) && (h = JSON.parse(h[1]).contents.twoColumnBrowseResultsRenderer.tabs)) {
  294. x = new RegExp(`^\\/[^\\/]+(?:\\/[^\\/]+)?\\/${tp}$`);
  295. if (h.some((v, i, b) => {
  296. if ((b = v.tabRenderer) && !b.content && x.test((b = b.endpoint).commandMetadata.webCommandMetadata.url)) {
  297. e = (ep = d).browseEndpoint;
  298. t = d.clickTrackingParams;
  299. m = d.commandMetadata;
  300. d.browseEndpoint = b.browseEndpoint;
  301. d.clickTrackingParams = b.clickTrackingParams;
  302. d.commandMetadata = b.commandMetadata;
  303. return true
  304. }
  305. })) {
  306. a.firstElementChild.click();
  307. setTimeout(() => {
  308. ep.browseEndpoint = e;
  309. ep.clickTrackingParams = t;
  310. ep.commandMetadata = m;
  311. }, 20)
  312. }
  313. }
  314. }))
  315. }
  316. }
  317.  
  318. function checkHotkeyPopup(a, b, c, d, e) {
  319. if ((a = document.querySelector("#sections.ytd-hotkey-dialog-content")) && !a.querySelector(".more-hotkeys")) {
  320. a.__shady_native_appendChild(b = (d = a.firstElementChild).__shady_native_cloneNode(false)).classList.add("more-hotkeys");
  321. a.__shady_native_appendChild(d.__shady_native_cloneNode(false));
  322. b.__shady_native_appendChild(d.__shady_native_firstElementChild.__shady_native_cloneNode(false)).textContent = "More Hotkeys";
  323. c = b.__shady_native_appendChild(d.__shady_native_lastElementChild.__shady_native_cloneNode(false));
  324. d = d.__shady_native_lastElementChild.firstElementChild;
  325. hotkeys.forEach((h, e, f) => {
  326. if (h.desc) {
  327. e = c.__shady_native_appendChild(d.__shady_native_cloneNode(true));
  328. e.__shady_native_firstElementChild.textContent = h.desc;
  329. if (!(f = h.keys)) {
  330. if (h.ctrl || h.alt) {
  331. f = (h.ctrl ? "CTRL+" : "") + (h.shift ? "SHIFT+" : "") + (h.alt ? "ALT+" : "") + h.key;
  332. } else if (h.shift) {
  333. f = h.key + " (" + (h.shift ? "SHIFT+" : "") + (h.shift ? baseKeys[h.key] || h.key.toLowerCase() : h.key) + ")";
  334. } else f = h.key.toLowerCase();
  335. }
  336. e.__shady_native_lastElementChild.textContent = f;
  337. }
  338. });
  339. } else if (--ch) setTimeout(checkHotkeyPopup, 100);
  340. }
  341.  
  342. function editable(e) {
  343. var r = false;
  344. while (e) {
  345. if (e.contentEditable === "true") return true;
  346. e = e.parentNode;
  347. }
  348. return r;
  349. }
  350.  
  351. if (top !== self) {
  352. addEventListener("message", ev => (ev.data === "myhujs_toggleChatChap") && toggleChatChap())
  353. }
  354.  
  355. hotkeys.forEach(h => {
  356. var a = h.mods.toUpperCase().split("");
  357. h.shift = a.includes("S");
  358. h.ctrl = a.includes("C");
  359. h.alt = a.includes("A");
  360. });
  361. addEventListener("keydown", (ev, a) => {
  362. if ((a = document.activeElement) && (editable(a) || (a.tagName === "INPUT") || (a.tagName === "TEXTAREA"))) return;
  363. if ((ev.key === "?") && ev.shiftKey && !ev.ctrlKey && !ev.altKey) {
  364. ch = 10;
  365. setTimeout(checkHotkeyPopup, 100);
  366. }
  367. hotkeys.forEach(h => {
  368. if ((ev.key.toUpperCase() === h.key) && (ev.shiftKey === h.shift) && (ev.ctrlKey === h.ctrl) && (ev.altKey === h.alt)) {
  369. ev.preventDefault();
  370. ("function" === typeof h.func) && h.func(h);
  371. }
  372. });
  373. }, true);
  374.  
  375. })();