BetterYTM.user.js 10 KB

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