BetterYTM.user.js 22 KB

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