BetterYTM.user.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. //#MARKER types
  49. /** @typedef {"yt"|"ytm"} Domain */
  50. //#MARKER init
  51. const info = Object.freeze({
  52. name: GM.info.script.name, // eslint-disable-line no-undef
  53. version: GM.info.script.version, // eslint-disable-line no-undef
  54. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  55. });
  56. function init()
  57. {
  58. try
  59. {
  60. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  61. document.addEventListener("DOMContentLoaded", onDomLoad);
  62. }
  63. catch(err)
  64. {
  65. console.error("BetterYTM - General Error:", err);
  66. }
  67. }
  68. //#MARKER events
  69. /**
  70. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  71. */
  72. function onDomLoad()
  73. {
  74. const domain = getDomain();
  75. // YTM-specific
  76. if(domain === "ytm")
  77. {
  78. if(features.arrowKeySupport)
  79. document.addEventListener("keydown", onKeyDown);
  80. if(features.removeUpgradeTab)
  81. removeUpgradeTab();
  82. if(!features.removeWatermark)
  83. addWatermark();
  84. }
  85. // Both YTM and YT
  86. if(features.switchBetweenSites)
  87. initSiteSwitch(domain);
  88. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  89. // applyTheme();
  90. }
  91. //#MARKER features
  92. //#SECTION arrow key skip
  93. /**
  94. * Called when the user presses keys
  95. * @param {KeyboardEvent} evt
  96. */
  97. function onKeyDown(evt)
  98. {
  99. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  100. {
  101. // 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
  102. const defaultProps = {
  103. altKey: false,
  104. bubbles: true,
  105. cancelBubble: false,
  106. cancelable: true,
  107. charCode: 0,
  108. composed: true,
  109. ctrlKey: false,
  110. currentTarget: null,
  111. defaultPrevented: evt.defaultPrevented,
  112. explicitOriginalTarget: document.body,
  113. isTrusted: true,
  114. metaKey: false,
  115. originalTarget: document.body,
  116. repeat: false,
  117. shiftKey: false,
  118. srcElement: document.body,
  119. target: document.body,
  120. type: "keydown",
  121. view: window,
  122. };
  123. let invalidKey = false;
  124. let keyProps = {};
  125. switch(evt.code)
  126. {
  127. case "ArrowLeft":
  128. keyProps = {
  129. code: "KeyH",
  130. key: "h",
  131. keyCode: 72,
  132. which: 72,
  133. };
  134. break;
  135. case "ArrowRight":
  136. keyProps = {
  137. code: "KeyL",
  138. key: "l",
  139. keyCode: 76,
  140. which: 76,
  141. };
  142. break;
  143. default:
  144. // console.warn("BetterYTM - Unknown key", evt.code);
  145. invalidKey = true;
  146. break;
  147. }
  148. if(!invalidKey)
  149. document.body.dispatchEvent(new KeyboardEvent("keydown", { ...defaultProps, ...keyProps }));
  150. }
  151. }
  152. //#SECTION site switch
  153. /**
  154. * Initializes the site switch feature
  155. * @param {Domain} domain
  156. */
  157. function initSiteSwitch(domain)
  158. {
  159. // TODO:
  160. // extra features:
  161. // - keep video time
  162. document.addEventListener("keydown", (e) => {
  163. if(e.key == "F9")
  164. switchSite(domain === "yt" ? "ytm" : "yt");
  165. });
  166. }
  167. /**
  168. * Switches to the other site (between YT and YTM)
  169. * @param {Domain} newDomain
  170. */
  171. function switchSite(newDomain)
  172. {
  173. console.log(`BYTM/Debug: Switching from domain ${getDomain()} to ${newDomain}`);
  174. try
  175. {
  176. let subdomain;
  177. if(newDomain === "ytm")
  178. subdomain = "music";
  179. else if(newDomain === "yt")
  180. subdomain = "www";
  181. if(!subdomain)
  182. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  183. const { pathname, search, hash } = new URL(location.href);
  184. const newSearch = search.includes("?") ? `${search}&t=${getVideoTime()}` : `?t=${getVideoTime()}`;
  185. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  186. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  187. location.href = url;
  188. }
  189. catch(err)
  190. {
  191. console.error(err instanceof Error ? err : new Error(err));
  192. }
  193. }
  194. //#SECTION remove upgrade tab
  195. /**
  196. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  197. */
  198. function removeUpgradeTab()
  199. {
  200. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  201. tabElem.remove();
  202. }
  203. //#SECTION add watermark
  204. /**
  205. * Adds a watermark beneath the logo
  206. */
  207. function addWatermark()
  208. {
  209. const watermark = document.createElement("a");
  210. watermark.id = "betterytm-watermark";
  211. watermark.className = "style-scope ytmusic-nav-bar";
  212. watermark.innerText = info.name;
  213. watermark.title = `${info.name} v${info.version}`;
  214. watermark.href = info.namespace;
  215. watermark.target = "_blank";
  216. watermark.rel = "noopener noreferrer";
  217. const style = `
  218. #betterytm-watermark {
  219. position: absolute;
  220. left: 45px;
  221. top: 43px;
  222. z-index: 10;
  223. color: white;
  224. text-decoration: none;
  225. cursor: pointer;
  226. }
  227. #betterytm-watermark:hover {
  228. text-decoration: underline;
  229. }
  230. `;
  231. const styleElem = document.createElement("style");
  232. styleElem.id = "betterytm-watermark-style";
  233. if(styleElem.styleSheet)
  234. styleElem.styleSheet.cssText = style;
  235. else
  236. styleElem.appendChild(document.createTextNode(style));
  237. document.querySelector("head").appendChild(styleElem);
  238. const logoElem = document.querySelector("#left-content");
  239. logoElem.parentNode.insertBefore(watermark, logoElem.nextSibling);
  240. }
  241. //#MARKER other
  242. /**
  243. * Returns the current domain as a constant string representation
  244. * @returns {Domain}
  245. */
  246. function getDomain()
  247. {
  248. const { hostname } = new URL(location.href);
  249. return hostname.toLowerCase().includes("music") ? "ytm" : "yt"; // other cases are caught by the `@match`es at the top
  250. }
  251. /**
  252. * Returns the current video time in seconds
  253. * @returns {number|null} Returns null if video time is unavailable
  254. */
  255. function getVideoTime()
  256. {
  257. const domain = getDomain();
  258. try
  259. {
  260. if(domain === "ytm")
  261. {
  262. const pbEl = document.querySelector("#progress-bar");
  263. return pbEl.value ?? null;
  264. }
  265. 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
  266. return 0;
  267. return null;
  268. }
  269. catch(err)
  270. {
  271. console.error("BetterYTM: Couldn't get video time due to error:", err);
  272. return null;
  273. }
  274. }
  275. init(); // call init() when script is loaded
  276. })();