BetterYTM.user.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @name:de BetterYTM
  4. // @namespace https://github.com/Sv443/BetterYTM#readme
  5. // @version 0.2.0
  6. // @license MIT
  7. // @author Sv443
  8. // @copyright Sv443 <[email protected]> (https://github.com/Sv443)
  9. // @description Improvements for YouTube Music
  10. // @description:de Verbesserungen für YouTube Music
  11. // @match https://music.youtube.com/*
  12. // @match https://www.youtube.com/*
  13. // @icon https://www.google.com/s2/favicons?domain=music.youtube.com
  14. // @run-at document-start
  15. // @connect self
  16. // @connect youtube.com
  17. // @connect github.com
  18. // @connect githubusercontent.com
  19. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  20. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  21. // ==/UserScript==
  22. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  23. /* C&D this, Susan 🖕 */
  24. (() => {
  25. "use-strict";
  26. /*
  27. █▀▀█ ▄▄▄ █ █ ▀ ▄▄▄ ▄▄▄▄ ▄▄▄
  28. ▀▀▄▄ █▄█ █▀ █▀ ▀█ █ █ █ ▄▄ █▄▄ ▀
  29. █▄▄█ █▄▄ █▄▄ █▄▄ ▄█▄ █ █ █▄▄█ ▄▄█ ▄
  30. */
  31. /**
  32. * This is where you can enable or disable features
  33. * If this userscript ever becomes something I might add like a menu to toggle these
  34. */
  35. const features = Object.freeze({
  36. // --- Quality of Life ---
  37. /** Whether arrow keys should skip forwards and backwards by 10 seconds */
  38. arrowKeySupport: true,
  39. /** Whether to remove the "Upgrade" / YT Music Premium tab */
  40. removeUpgradeTab: true,
  41. // --- Extra Features ---
  42. /** Whether to add a button or key combination (TODO) to switch between the YT and YTM sites on a video */
  43. switchBetweenSites: true,
  44. /** Adds a button to the media controls bar to open the current song's genius.com lyrics in a new tab */
  45. geniusLyrics: true,
  46. // --- Other ---
  47. /** Set to true to remove the watermark under the YTM logo */
  48. removeWatermark: false,
  49. // /** The theme color - accepts any CSS color value - default is "#ff0000" */
  50. // themeColor: "#0f0",
  51. });
  52. /** Set to true to enable debug mode for more output in the JS console */
  53. const dbg = true;
  54. //#MARKER types
  55. /** @typedef {"yt"|"ytm"} Domain */
  56. //#MARKER init
  57. const info = Object.freeze({
  58. name: GM.info.script.name, // eslint-disable-line no-undef
  59. version: GM.info.script.version, // eslint-disable-line no-undef
  60. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  61. });
  62. function init()
  63. {
  64. try
  65. {
  66. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  67. document.addEventListener("DOMContentLoaded", onDomLoad);
  68. }
  69. catch(err)
  70. {
  71. console.error("BetterYTM - General Error:", err);
  72. }
  73. }
  74. //#MARKER events
  75. /**
  76. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  77. */
  78. function onDomLoad()
  79. {
  80. const domain = getDomain();
  81. dbg && console.info(`BetterYTM: Initializing features for domain '${domain}'`);
  82. try
  83. {
  84. // YTM-specific
  85. if(domain === "ytm")
  86. {
  87. if(features.arrowKeySupport)
  88. {
  89. document.addEventListener("keydown", onKeyDown);
  90. dbg && console.info(`BetterYTM: Added key press listener`);
  91. }
  92. if(features.removeUpgradeTab)
  93. removeUpgradeTab();
  94. if(!features.removeWatermark)
  95. addWatermark();
  96. if(features.geniusLyrics)
  97. addGeniusButton();
  98. }
  99. // Both YTM and YT
  100. if(features.switchBetweenSites)
  101. initSiteSwitch(domain);
  102. }
  103. catch(err)
  104. {
  105. console.error(`BetterYTM: General error while executing feature:`, err);
  106. }
  107. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  108. // applyTheme();
  109. }
  110. //#MARKER features
  111. //#SECTION arrow key skip
  112. /**
  113. * Called when the user presses keys
  114. * @param {KeyboardEvent} evt
  115. */
  116. function onKeyDown(evt)
  117. {
  118. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  119. {
  120. dbg && console.info(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  121. // ripped this stuff from the console, most of these are probably unnecessary but this was finnicky af and I am sick and tired of trial and error
  122. const defaultProps = {
  123. altKey: false,
  124. bubbles: true,
  125. cancelBubble: false,
  126. cancelable: true,
  127. charCode: 0,
  128. composed: true,
  129. ctrlKey: false,
  130. currentTarget: null,
  131. defaultPrevented: evt.defaultPrevented,
  132. explicitOriginalTarget: document.body,
  133. isTrusted: true,
  134. metaKey: false,
  135. originalTarget: document.body,
  136. repeat: false,
  137. shiftKey: false,
  138. srcElement: document.body,
  139. target: document.body,
  140. type: "keydown",
  141. view: window,
  142. };
  143. let invalidKey = false;
  144. let keyProps = {};
  145. switch(evt.code)
  146. {
  147. case "ArrowLeft":
  148. keyProps = {
  149. code: "KeyH",
  150. key: "h",
  151. keyCode: 72,
  152. which: 72,
  153. };
  154. break;
  155. case "ArrowRight":
  156. keyProps = {
  157. code: "KeyL",
  158. key: "l",
  159. keyCode: 76,
  160. which: 76,
  161. };
  162. break;
  163. default:
  164. // console.warn("BetterYTM - Unknown key", evt.code);
  165. invalidKey = true;
  166. break;
  167. }
  168. if(!invalidKey)
  169. {
  170. const proxyProps = { ...defaultProps, ...keyProps };
  171. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  172. dbg && console.info(`BetterYTM: Dispatched proxy keydown event [${evt.code}] -> [${proxyProps.code}]`);
  173. }
  174. else if(dbg)
  175. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  176. }
  177. }
  178. //#SECTION site switch
  179. /**
  180. * Initializes the site switch feature
  181. * @param {Domain} domain
  182. */
  183. function initSiteSwitch(domain)
  184. {
  185. // TODO:
  186. // extra features:
  187. // - keep video time
  188. document.addEventListener("keydown", (e) => {
  189. if(e.key == "F9")
  190. switchSite(domain === "yt" ? "ytm" : "yt");
  191. });
  192. dbg && console.info(`BetterYTM: Initialized site switch listener`);
  193. }
  194. /**
  195. * Switches to the other site (between YT and YTM)
  196. * @param {Domain} newDomain
  197. */
  198. function switchSite(newDomain)
  199. {
  200. dbg && console.info(`BetterYTM: Switching from domain '${getDomain()}' to '${newDomain}'`);
  201. try
  202. {
  203. let subdomain;
  204. if(newDomain === "ytm")
  205. subdomain = "music";
  206. else if(newDomain === "yt")
  207. subdomain = "www";
  208. if(!subdomain)
  209. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  210. const { pathname, search, hash } = new URL(location.href);
  211. const vt = getVideoTime() ?? 0;
  212. dbg && console.info(`BetterYTM: Found video time of ${vt} seconds`);
  213. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  214. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  215. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  216. location.href = url;
  217. }
  218. catch(err)
  219. {
  220. console.error(`BetterYTM: Error while switching site:`, err);
  221. }
  222. }
  223. //#SECTION remove upgrade tab
  224. let removeUpgradeTries = 0;
  225. /**
  226. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  227. */
  228. function removeUpgradeTab()
  229. {
  230. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  231. if(tabElem)
  232. {
  233. tabElem.remove();
  234. dbg && console.info(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  235. }
  236. else if(removeUpgradeTries < 10)
  237. {
  238. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  239. removeUpgradeTries++;
  240. }
  241. else if(dbg)
  242. console.info(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  243. }
  244. //#SECTION add watermark
  245. /**
  246. * Adds a watermark beneath the logo
  247. */
  248. function addWatermark()
  249. {
  250. const watermark = document.createElement("a");
  251. watermark.id = "betterytm-watermark";
  252. watermark.className = "style-scope ytmusic-nav-bar";
  253. watermark.innerText = info.name;
  254. watermark.title = `${info.name} v${info.version}`;
  255. watermark.href = info.namespace;
  256. watermark.target = "_blank";
  257. watermark.rel = "noopener noreferrer";
  258. const style = `
  259. #betterytm-watermark {
  260. position: absolute;
  261. left: 45px;
  262. top: 43px;
  263. z-index: 10;
  264. color: white;
  265. text-decoration: none;
  266. cursor: pointer;
  267. }
  268. #betterytm-watermark:hover {
  269. text-decoration: underline;
  270. }
  271. `;
  272. const styleElem = document.createElement("style");
  273. styleElem.id = "betterytm-watermark-style";
  274. if(styleElem.styleSheet)
  275. styleElem.styleSheet.cssText = style;
  276. else
  277. styleElem.appendChild(document.createTextNode(style));
  278. document.querySelector("head").appendChild(styleElem);
  279. const logoElem = document.querySelector("#left-content");
  280. logoElem.parentNode.insertBefore(watermark, logoElem.nextSibling);
  281. dbg && console.info(`BetterYTM: Added watermark element:`, watermark);
  282. }
  283. //#SECTION genius.com lyrics button
  284. function addGeniusButton()
  285. {
  286. const menuElem = document.querySelector(".middle-controls-buttons tp-yt-paper-icon-button.dropdown-trigger");
  287. if(!menuElem)
  288. return setTimeout(addGeniusButton, 250);
  289. const linkElem = document.createElement("a");
  290. linkElem.id = "betterytm-genius-button";
  291. linkElem.href = getGeniusUrl();
  292. linkElem.target = "_blank";
  293. linkElem.rel = "noopener noreferrer";
  294. const imgElem = document.createElement("img");
  295. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/develop/resources/external/genius.png";
  296. imgElem.style = "z-index: 10; width: 24px; height: 24px; padding: 8px; padding-left: 16px;";
  297. linkElem.appendChild(imgElem);
  298. dbg && console.info(`BetterYTM: Inserted genius button:`, linkElem);
  299. menuElem.parentNode.insertBefore(linkElem, menuElem.nextSibling);
  300. }
  301. //#MARKER other
  302. /**
  303. * Returns the current domain as a constant string representation
  304. * @returns {Domain}
  305. */
  306. function getDomain()
  307. {
  308. const { hostname } = new URL(location.href);
  309. return hostname.toLowerCase().includes("music") ? "ytm" : "yt"; // other cases are caught by the `@match`es at the top
  310. }
  311. /**
  312. * Returns the current video time in seconds
  313. * @returns {number|null} Returns null if video time is unavailable
  314. */
  315. function getVideoTime()
  316. {
  317. const domain = getDomain();
  318. try
  319. {
  320. if(domain === "ytm")
  321. {
  322. const pbEl = document.querySelector("#progress-bar");
  323. return pbEl.value ?? null;
  324. }
  325. else if(domain === "yt") // YT doesn't update the progress bar when it's hidden (YTM doesn't hide it) so TODO: come up with some solution here
  326. return 0;
  327. return null;
  328. }
  329. catch(err)
  330. {
  331. console.error("BetterYTM: Couldn't get video time due to error:", err);
  332. return null;
  333. }
  334. }
  335. init(); // call init() when script is loaded
  336. })();