BetterYTM.user.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. // ==UserScript==
  2. // @name BetterYTM
  3. // @name:de BetterYTM
  4. // @namespace https://github.com/Sv443/BetterYTM#readme
  5. // @version 1.0.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. // @grant GM.getValue
  16. // @grant GM.setValue
  17. // @connect self
  18. // @connect youtube.com
  19. // @connect github.com
  20. // @connect githubusercontent.com
  21. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  22. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  23. // ==/UserScript==
  24. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  25. /* C&D this, Susan 🖕 */
  26. (async () => {
  27. "use-strict";
  28. /** Set to true to enable debug mode for more output in the JS console */
  29. const dbg = true;
  30. const defaultFeatures = {
  31. /** Whether arrow keys should skip forwards and backwards by 10 seconds */
  32. arrowKeySupport: true,
  33. /** Whether to remove the "Upgrade" / YT Music Premium tab */
  34. removeUpgradeTab: true,
  35. /** Whether to add a key combination to switch between the YT and YTM sites on a video */
  36. switchBetweenSites: true,
  37. /** Adds a button to the media controls bar to search for the current song's lyrics on genius.com in a new tab */
  38. geniusLyrics: true,
  39. /** Adds a lyrics button to each song in the queue ("up next" tab) */
  40. lyricsButtonsOnSongQueue: true,
  41. /** Set to true to remove the watermark under the YTM logo */
  42. removeWatermark: false,
  43. };
  44. const featureConf = await loadFeatureConf();
  45. console.log("bytm load", featureConf);
  46. const features = { ...defaultFeatures, ...featureConf };
  47. console.log("bytm save", features);
  48. await saveFeatureConf(features);
  49. //#MARKER types
  50. /** @typedef {"yt"|"ytm"} Domain Constant string representation of which domain this script is currently running on */
  51. //#MARKER init
  52. /** Specifies the hard limit for repetitive tasks */
  53. const triesLimit = 20;
  54. /** Base URL of geniURL */
  55. const geniURLBaseUrl = "https://api.sv443.net/geniurl";
  56. /** GeniURL endpoint that gives song metadata when provided with a `?q` parameter - [more info](https://api.sv443.net/geniurl) */
  57. const geniURLSearchTopUrl = `${geniURLBaseUrl}/search/top`;
  58. const info = Object.freeze({
  59. name: GM.info.script.name, // eslint-disable-line no-undef
  60. version: GM.info.script.version, // eslint-disable-line no-undef
  61. namespace: GM.info.script.namespace, // eslint-disable-line no-undef
  62. });
  63. function init()
  64. {
  65. try
  66. {
  67. console.log(`${info.name} v${info.version} - ${info.namespace}`);
  68. console.log(`Powered by lots of ambition and my song metadata API called geniURL: ${geniURLBaseUrl}`);
  69. document.addEventListener("DOMContentLoaded", onDomLoad);
  70. }
  71. catch(err)
  72. {
  73. console.error("BetterYTM - General Error:", err);
  74. }
  75. }
  76. //#MARKER events
  77. /**
  78. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  79. */
  80. async function onDomLoad()
  81. {
  82. const domain = getDomain();
  83. dbg && console.log(`BetterYTM: Initializing features for domain '${domain}'`);
  84. try
  85. {
  86. if(domain === "ytm")
  87. {
  88. if(features.arrowKeySupport)
  89. {
  90. document.addEventListener("keydown", onKeyDown);
  91. dbg && console.log(`BetterYTM: Added key press listener`);
  92. }
  93. if(features.removeUpgradeTab)
  94. removeUpgradeTab();
  95. if(!features.removeWatermark)
  96. addWatermark();
  97. if(features.geniusLyrics)
  98. await addMediaCtrlGeniusBtn();
  99. if(features.lyricsButtonsOnSongQueue)
  100. await addQueueGeniusBtns();
  101. }
  102. if(["ytm", "yt"].includes(domain))
  103. {
  104. if(features.switchBetweenSites)
  105. initSiteSwitch(domain);
  106. try
  107. {
  108. addMenu();
  109. }
  110. catch(err)
  111. {
  112. console.error("BetterYTM: Couldn't add menu:", err);
  113. }
  114. }
  115. }
  116. catch(err)
  117. {
  118. console.error(`BetterYTM: General error while executing feature:`, err);
  119. }
  120. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  121. // applyTheme();
  122. }
  123. //#MARKER menu
  124. /**
  125. * Adds an element to open the BetterYTM menu
  126. */
  127. function addMenu()
  128. {
  129. // const domain = getDomain();
  130. // bg & menu
  131. const backgroundElem = document.createElement("div");
  132. backgroundElem.id = "betterytm-menu-bg";
  133. backgroundElem.title = "Click here to close the menu";
  134. backgroundElem.style.visibility = "hidden";
  135. backgroundElem.style.display = "none";
  136. backgroundElem.addEventListener("click", (e) => {
  137. if(e.target.id === "betterytm-menu-bg")
  138. closeMenu();
  139. });
  140. const menuContainer = document.createElement("div");
  141. menuContainer.title = "";
  142. menuContainer.id = "betterytm-menu";
  143. // title
  144. const titleCont = document.createElement("div");
  145. titleCont.id = "betterytm-menu-titlecont";
  146. const titleElem = document.createElement("h2");
  147. titleElem.id = "betterytm-menu-title";
  148. titleElem.innerText = "BetterYTM - Menu";
  149. const linksCont = document.createElement("div");
  150. linksCont.id = "betterytm-menu-linkscont";
  151. const addLink = (imgSrc, href, title) => {
  152. const anchorElem = document.createElement("a");
  153. anchorElem.className = "betterytm-menu-link";
  154. anchorElem.rel = "noopener noreferrer";
  155. anchorElem.target = "_blank";
  156. anchorElem.href = href;
  157. anchorElem.title = title;
  158. const linkElem = document.createElement("img");
  159. linkElem.className = "betterytm-menu-img";
  160. linkElem.src = imgSrc;
  161. anchorElem.appendChild(linkElem);
  162. linksCont.appendChild(anchorElem);
  163. };
  164. addLink("TODO:github.png", info.namespace, `${info.name} on GitHub`);
  165. addLink("TODO:greasyfork.png", "https://greasyfork.org/", `${info.name} on GreasyFork`);
  166. const closeElem = document.createElement("img");
  167. closeElem.id = "betterytm-menu-close";
  168. closeElem.src = "TODO:close.png";
  169. closeElem.title = "Click to close the menu";
  170. closeElem.addEventListener("click", closeMenu);
  171. titleCont.appendChild(titleElem);
  172. titleCont.appendChild(linksCont);
  173. titleCont.appendChild(closeElem);
  174. // TODO: features
  175. const featuresCont = document.createElement("div");
  176. featuresCont.id = "betterytm-menu-opts";
  177. // finalize
  178. menuContainer.appendChild(titleCont);
  179. menuContainer.appendChild(featuresCont);
  180. backgroundElem.appendChild(menuContainer);
  181. document.body.appendChild(backgroundElem);
  182. // add style
  183. const menuStyle = `\
  184. #betterytm-menu-bg {
  185. display: block;
  186. position: fixed;
  187. width: 100vw;
  188. height: 100vh;
  189. top: 0;
  190. left: 0;
  191. z-index: 15;
  192. background-color: rgba(0, 0, 0, 0.6);
  193. }
  194. #betterytm-menu {
  195. display: inline-block;
  196. position: fixed;
  197. width: 50vw;
  198. height: 50vh;
  199. min-height: 500px;
  200. left: 25vw;
  201. top: 25vh;
  202. z-index: 16;
  203. overflow: auto;
  204. padding: 8px;
  205. color: #fff;
  206. background-color: #212121;
  207. }
  208. #betterytm-menu-titlecont {
  209. display: flex;
  210. }
  211. #betterytm-menu-title {
  212. font-size: 20px;
  213. margin-top: 5px;
  214. margin-bottom: 8px;
  215. }
  216. #betterytm-menu-linkscont {
  217. display: flex;
  218. }
  219. .betterytm-menu-link {
  220. display: inline-block;
  221. }
  222. .betterytm-menu-img {
  223. }
  224. #betterytm-menu-close {
  225. cursor: pointer;
  226. }
  227. `;
  228. dbg && console.log("BetterYTM: Added menu elem:", backgroundElem);
  229. /* #DEBUG */ //openMenu();
  230. addGlobalStyle(menuStyle, "menu");
  231. }
  232. function closeMenu()
  233. {
  234. const menuBg = document.querySelector("#betterytm-menu-bg");
  235. menuBg.style.visibility = "hidden";
  236. menuBg.style.display = "none";
  237. }
  238. // function openMenu()
  239. // {
  240. // const menuBg = document.querySelector("#betterytm-menu-bg");
  241. // menuBg.style.visibility = "visible";
  242. // menuBg.style.display = "block";
  243. // }
  244. //#MARKER features
  245. //#SECTION arrow key skip
  246. /**
  247. * Called when the user presses keys
  248. * @param {KeyboardEvent} evt
  249. */
  250. function onKeyDown(evt)
  251. {
  252. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  253. {
  254. // discard the event when a (text) input is currently active, like when editing a playlist
  255. if(["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName))
  256. return dbg && console.info(`BetterYTM: Captured valid key but the current active element is <${document.activeElement.tagName.toLowerCase()}>, so the keypress is ignored`);
  257. dbg && console.log(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  258. // 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
  259. const defaultProps = {
  260. altKey: false,
  261. bubbles: true,
  262. cancelBubble: false,
  263. cancelable: true,
  264. charCode: 0,
  265. composed: true,
  266. ctrlKey: false,
  267. currentTarget: null,
  268. defaultPrevented: evt.defaultPrevented,
  269. explicitOriginalTarget: document.body,
  270. isTrusted: true,
  271. metaKey: false,
  272. originalTarget: document.body,
  273. repeat: false,
  274. shiftKey: false,
  275. srcElement: document.body,
  276. target: document.body,
  277. type: "keydown",
  278. view: window,
  279. };
  280. let invalidKey = false;
  281. let keyProps = {};
  282. switch(evt.code)
  283. {
  284. case "ArrowLeft":
  285. keyProps = {
  286. code: "KeyH",
  287. key: "h",
  288. keyCode: 72,
  289. which: 72,
  290. };
  291. break;
  292. case "ArrowRight":
  293. keyProps = {
  294. code: "KeyL",
  295. key: "l",
  296. keyCode: 76,
  297. which: 76,
  298. };
  299. break;
  300. default:
  301. // console.warn("BetterYTM - Unknown key", evt.code);
  302. invalidKey = true;
  303. break;
  304. }
  305. if(!invalidKey)
  306. {
  307. const proxyProps = { ...defaultProps, ...keyProps };
  308. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  309. dbg && console.log(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  310. }
  311. else if(dbg)
  312. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  313. }
  314. }
  315. //#SECTION site switch
  316. /**
  317. * Initializes the site switch feature
  318. * @param {Domain} domain
  319. */
  320. function initSiteSwitch(domain)
  321. {
  322. // TODO:
  323. // extra features:
  324. // - keep video time
  325. document.addEventListener("keydown", (e) => {
  326. if(e.key == "F9")
  327. switchSite(domain === "yt" ? "ytm" : "yt");
  328. });
  329. dbg && console.log(`BetterYTM: Initialized site switch listener`);
  330. }
  331. /**
  332. * Switches to the other site (between YT and YTM)
  333. * @param {Domain} newDomain
  334. */
  335. function switchSite(newDomain)
  336. {
  337. try
  338. {
  339. let subdomain;
  340. if(newDomain === "ytm")
  341. subdomain = "music";
  342. else if(newDomain === "yt")
  343. subdomain = "www";
  344. if(!subdomain)
  345. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  346. const { pathname, search, hash } = new URL(location.href);
  347. const vt = getVideoTime() ?? 0;
  348. dbg && console.log(`BetterYTM: Found video time of ${vt} seconds`);
  349. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  350. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  351. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  352. location.href = url;
  353. }
  354. catch(err)
  355. {
  356. console.error(`BetterYTM: Error while switching site:`, err);
  357. }
  358. }
  359. //#SECTION remove upgrade tab
  360. let removeUpgradeTries = 0;
  361. /**
  362. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  363. */
  364. function removeUpgradeTab()
  365. {
  366. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  367. if(tabElem)
  368. {
  369. tabElem.remove();
  370. dbg && console.log(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  371. }
  372. else if(removeUpgradeTries < triesLimit)
  373. {
  374. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  375. removeUpgradeTries++;
  376. }
  377. else
  378. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  379. }
  380. //#SECTION add watermark
  381. /**
  382. * Adds a watermark beneath the logo
  383. */
  384. function addWatermark()
  385. {
  386. const watermark = document.createElement("a");
  387. watermark.id = "betterytm-watermark";
  388. watermark.className = "style-scope ytmusic-nav-bar";
  389. watermark.innerText = info.name;
  390. watermark.title = `${info.name} v${info.version}`;
  391. watermark.href = info.namespace;
  392. watermark.target = "_blank";
  393. watermark.rel = "noopener noreferrer";
  394. const style = `\
  395. #betterytm-watermark {
  396. display: inline-block;
  397. position: absolute;
  398. left: 45px;
  399. top: 43px;
  400. z-index: 10;
  401. color: white;
  402. text-decoration: none;
  403. cursor: pointer;
  404. }
  405. @media(max-width: 615px) {
  406. #betterytm-watermark {
  407. display: none;
  408. }
  409. }
  410. #betterytm-watermark:hover {
  411. text-decoration: underline;
  412. }`;
  413. addGlobalStyle(style, "watermark");
  414. const logoElem = document.querySelector("#left-content");
  415. insertAfter(logoElem, watermark);
  416. dbg && console.log(`BetterYTM: Added watermark element:`, watermark);
  417. }
  418. //#SECTION genius.com lyrics button
  419. let mcCurrentSongTitle = "";
  420. let mcLyricsButtonAddTries = 0;
  421. /**
  422. * Adds a genius.com lyrics button to the media controls bar
  423. */
  424. async function addMediaCtrlGeniusBtn()
  425. {
  426. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  427. if(!likeContainer)
  428. {
  429. mcLyricsButtonAddTries++;
  430. if(mcLyricsButtonAddTries < triesLimit)
  431. return setTimeout(addMediaCtrlGeniusBtn, 250); // TODO: improve this
  432. return console.error(`BetterYTM: Couldn't find element to append lyrics buttons to after ${mcLyricsButtonAddTries} tries`);
  433. }
  434. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  435. const gUrl = await getCurrentGeniusUrl();
  436. const linkElem = document.createElement("a");
  437. linkElem.id = "betterytm-lyrics-button";
  438. linkElem.className = "ytmusic-player-bar";
  439. linkElem.title = "Search for lyrics on genius.com";
  440. linkElem.href = gUrl;
  441. linkElem.target = "_blank";
  442. linkElem.rel = "noopener noreferrer";
  443. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  444. const style = `\
  445. #betterytm-lyrics-button {
  446. display: inline-flex;
  447. align-items: center;
  448. justify-content: center;
  449. position: relative;
  450. vertical-align: middle;
  451. margin-left: 8px;
  452. width: 40px;
  453. height: 40px;
  454. border-radius: 100%;
  455. background-color: transparent;
  456. }
  457. #betterytm-lyrics-button:hover {
  458. background-color: #383838;
  459. }
  460. #betterytm-lyrics-img {
  461. display: inline-block;
  462. z-index: 10;
  463. width: 24px;
  464. height: 24px;
  465. padding: 5px;
  466. }`;
  467. addGlobalStyle(style, "lyrics");
  468. const imgElem = document.createElement("img");
  469. imgElem.id = "betterytm-lyrics-img";
  470. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  471. linkElem.appendChild(imgElem);
  472. dbg && console.log(`BetterYTM: Inserted genius button after ${mcLyricsButtonAddTries} tries:`, linkElem);
  473. insertAfter(likeContainer, linkElem);
  474. mcCurrentSongTitle = songTitleElem.title;
  475. /** @param {MutationRecord[]} mutations */
  476. const onMutation = async (mutations) => {
  477. for await(const mut of mutations)
  478. {
  479. const newTitle = mut.target.title;
  480. if(newTitle != mcCurrentSongTitle)
  481. {
  482. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  483. dbg && console.log(`BetterYTM: Song title changed from '${mcCurrentSongTitle}' to '${newTitle}'`);
  484. lyricsBtn.style.cursor = "wait";
  485. lyricsBtn.style.pointerEvents = "none";
  486. mcCurrentSongTitle = newTitle;
  487. lyricsBtn.href = await getCurrentGeniusUrl(); // can take a second or two
  488. lyricsBtn.style.cursor = "pointer";
  489. lyricsBtn.style.visibility = "initial";
  490. lyricsBtn.style.pointerEvents = "initial";
  491. }
  492. }
  493. };
  494. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  495. const obs = new MutationObserver(onMutation);
  496. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  497. }
  498. /**
  499. * Adds genius lyrics buttons to the song queue
  500. */
  501. async function addQueueGeniusBtns()
  502. {
  503. }
  504. /**
  505. * Returns the genius.com lyrics site URL for the current song
  506. * @returns {string|null}
  507. */
  508. async function getCurrentGeniusUrl()
  509. {
  510. try
  511. {
  512. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  513. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  514. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  515. return null;
  516. /** @param {string} songName */
  517. const sanitizeSongName = (songName) => {
  518. let sanitized;
  519. if(songName.match(/\(|feat|ft/gmi))
  520. sanitized = songName.replace(/(\(|feat|ft).*$/gmi); // should hopefully trim right after the song name
  521. return (sanitized || songName).trim();
  522. };
  523. /** @param {string} songMeta */
  524. const splitArtist = (songMeta) => {
  525. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; (•) character
  526. if(songMeta.match(/&/))
  527. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  528. if(songMeta.match(/,/))
  529. songMeta = songMeta.split(/,\s*/gm)[0];
  530. return songMeta.trim();
  531. }
  532. const songNameRaw = songTitleElem.title;
  533. const songName = sanitizeSongName(songNameRaw);
  534. const artistName = splitArtist(songMetaElem.title);
  535. // TODO: artist might need further splitting before comma or ampersand
  536. const query = encodeURIComponent(`${artistName} ${songName}`);
  537. return getGeniusUrl(query);
  538. }
  539. catch(err)
  540. {
  541. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  542. }
  543. }
  544. /**
  545. * @param {string} query
  546. * @returns {string|null}
  547. */
  548. async function getGeniusUrl(query)
  549. {
  550. const result = await (await fetch(`${geniURLSearchTopUrl}?q=${query}`)).json();
  551. if(result.error)
  552. {
  553. console.error("BetterYTM: Couldn't fetch genius.com URL:", result.message);
  554. return null;
  555. }
  556. return result.url;
  557. }
  558. //#MARKER other
  559. /**
  560. * Returns the current domain as a constant string representation
  561. * @throws {Error} If script runs on an unexpected website
  562. * @returns {Domain}
  563. */
  564. function getDomain()
  565. {
  566. const { hostname } = new URL(location.href);
  567. if(hostname.includes("music.youtube"))
  568. return "ytm";
  569. else if(hostname.includes("youtube"))
  570. return "yt";
  571. else
  572. throw new Error("BetterYTM is running on an unexpected website");
  573. }
  574. /**
  575. * TODO: this is entirely broken now
  576. * Returns the current video time in seconds
  577. * @returns {number|null} Returns null if the video time is unavailable
  578. */
  579. function getVideoTime()
  580. {
  581. const domain = getDomain();
  582. try
  583. {
  584. if(domain === "ytm")
  585. {
  586. const pbEl = document.querySelector("#progress-bar");
  587. return pbEl.value ?? null;
  588. }
  589. 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
  590. return 0;
  591. return null;
  592. }
  593. catch(err)
  594. {
  595. console.error("BetterYTM: Couldn't get video time due to error:", err);
  596. return null;
  597. }
  598. }
  599. /**
  600. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  601. * @param {HTMLElement} beforeNode
  602. * @param {HTMLElement} afterNode
  603. * @returns {HTMLElement} Returns the `afterNode`
  604. */
  605. function insertAfter(beforeNode, afterNode)
  606. {
  607. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  608. return afterNode;
  609. }
  610. /**
  611. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  612. * @param {string} style CSS string
  613. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  614. */
  615. function addGlobalStyle(style, ref)
  616. {
  617. const styleElem = document.createElement("style");
  618. styleElem.id = `betterytm-${ref}-style`;
  619. if(styleElem.styleSheet)
  620. styleElem.styleSheet.cssText = style;
  621. else
  622. styleElem.appendChild(document.createTextNode(style));
  623. document.querySelector("head").appendChild(styleElem);
  624. dbg && console.log(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  625. }
  626. /**
  627. * Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved
  628. * @returns {Promise<Readonly<typeof defaultFeatures | {}>>}
  629. */
  630. async function loadFeatureConf()
  631. {
  632. /** @type {string} */
  633. const featureConf = await GM.getValue("bytm-featureconf"); // eslint-disable-line no-undef
  634. return Object.freeze(featureConf ? JSON.parse(featureConf) : {});
  635. }
  636. /**
  637. * Saves a feature configuration saved persistently
  638. * @param {typeof defaultFeatures} featureConf
  639. * @returns {Promise<void>}
  640. */
  641. function saveFeatureConf(featureConf)
  642. {
  643. if(!featureConf || typeof featureConf != "object")
  644. throw new TypeError("Feature config not provided or invalid");
  645. return GM.setValue("bytm-featureconf", JSON.stringify(featureConf)); // eslint-disable-line no-undef
  646. }
  647. init(); // call init() when script is loaded
  648. })();