BetterYTM.user.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. // @match https://genius.com/search*
  14. // @icon https://www.google.com/s2/favicons?domain=music.youtube.com
  15. // @run-at document-start
  16. // @grant GM.getValue
  17. // @grant GM.setValue
  18. // @connect self
  19. // @connect youtube.com
  20. // @connect github.com
  21. // @connect githubusercontent.com
  22. // @downloadURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  23. // @updateURL https://raw.githubusercontent.com/Sv443/BetterYTM/main/BetterYTM.user.js
  24. // @require https://cdn.jsdelivr.net/npm/fuse.js/dist/fuse.js
  25. // ==/UserScript==
  26. /* Disclaimer: I am not affiliated with YouTube, Google, Alphabet, Genius or anyone else */
  27. /* C&D this, Susan 🖕 */
  28. (async () => {
  29. "use-strict";
  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 button or key combination (TODO) 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. /** This option makes the genius.com lyrics search button from above automatically open the best matching result */
  40. geniusAutoclickBestResult: true,
  41. /** Whether to add a border around the best matching result to visualize it before redirecting */
  42. visualizeBestResult: true,
  43. /** Set to true to remove the watermark under the YTM logo */
  44. removeWatermark: false,
  45. };
  46. const featureConf = await loadFeatureConf();
  47. console.log("bytm load", featureConf);
  48. const features = { ...defaultFeatures, ...featureConf };
  49. console.log("bytm save", features);
  50. await saveFeatureConf(features);
  51. /** Set to true to enable debug mode for more output in the JS console */
  52. const dbg = false;
  53. //#MARKER types
  54. /** @typedef {"yt"|"ytm"|"genius"} Domain Constant string representation of which domain this script is currently running on */
  55. //#MARKER init
  56. /** Specifies the hard limit for repetitive tasks */
  57. const triesLimit = 20;
  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. document.addEventListener("DOMContentLoaded", onDomLoad);
  69. }
  70. catch(err)
  71. {
  72. console.error("BetterYTM - General Error:", err);
  73. }
  74. }
  75. //#MARKER events
  76. /**
  77. * Called when the DOM has finished loading (after `DOMContentLoaded` is emitted)
  78. */
  79. function onDomLoad()
  80. {
  81. const domain = getDomain();
  82. dbg && console.info(`BetterYTM: Initializing features for domain '${domain}'`);
  83. try
  84. {
  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. if(["ytm", "yt"].includes(domain))
  100. {
  101. if(features.switchBetweenSites)
  102. initSiteSwitch(domain);
  103. }
  104. if(domain === "genius")
  105. {
  106. if(features.geniusAutoclickBestResult)
  107. autoclickGeniusResult();
  108. }
  109. }
  110. catch(err)
  111. {
  112. console.error(`BetterYTM: General error while executing feature:`, err);
  113. }
  114. // if(features.themeColor != "#f00" && features.themeColor != "#ff0000")
  115. // applyTheme();
  116. }
  117. //#MARKER features
  118. //#SECTION arrow key skip
  119. /**
  120. * Called when the user presses keys
  121. * @param {KeyboardEvent} evt
  122. */
  123. function onKeyDown(evt)
  124. {
  125. if(["ArrowLeft", "ArrowRight"].includes(evt.code))
  126. {
  127. dbg && console.info(`BetterYTM: Captured key '${evt.code}' in proxy listener`);
  128. // 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
  129. const defaultProps = {
  130. altKey: false,
  131. bubbles: true,
  132. cancelBubble: false,
  133. cancelable: true,
  134. charCode: 0,
  135. composed: true,
  136. ctrlKey: false,
  137. currentTarget: null,
  138. defaultPrevented: evt.defaultPrevented,
  139. explicitOriginalTarget: document.body,
  140. isTrusted: true,
  141. metaKey: false,
  142. originalTarget: document.body,
  143. repeat: false,
  144. shiftKey: false,
  145. srcElement: document.body,
  146. target: document.body,
  147. type: "keydown",
  148. view: window,
  149. };
  150. let invalidKey = false;
  151. let keyProps = {};
  152. switch(evt.code)
  153. {
  154. case "ArrowLeft":
  155. keyProps = {
  156. code: "KeyH",
  157. key: "h",
  158. keyCode: 72,
  159. which: 72,
  160. };
  161. break;
  162. case "ArrowRight":
  163. keyProps = {
  164. code: "KeyL",
  165. key: "l",
  166. keyCode: 76,
  167. which: 76,
  168. };
  169. break;
  170. default:
  171. // console.warn("BetterYTM - Unknown key", evt.code);
  172. invalidKey = true;
  173. break;
  174. }
  175. if(!invalidKey)
  176. {
  177. const proxyProps = { ...defaultProps, ...keyProps };
  178. document.body.dispatchEvent(new KeyboardEvent("keydown", proxyProps));
  179. dbg && console.info(`BetterYTM: Dispatched proxy keydown event: [${evt.code}] -> [${proxyProps.code}]`);
  180. }
  181. else if(dbg)
  182. console.warn(`BetterYTM: Captured key '${evt.code}' has no defined behavior`);
  183. }
  184. }
  185. //#SECTION site switch
  186. /**
  187. * Initializes the site switch feature
  188. * @param {Domain} domain
  189. */
  190. function initSiteSwitch(domain)
  191. {
  192. // TODO:
  193. // extra features:
  194. // - keep video time
  195. document.addEventListener("keydown", (e) => {
  196. if(e.key == "F9")
  197. switchSite(domain === "yt" ? "ytm" : "yt");
  198. });
  199. dbg && console.info(`BetterYTM: Initialized site switch listener`);
  200. }
  201. /**
  202. * Switches to the other site (between YT and YTM)
  203. * @param {Domain} newDomain
  204. */
  205. function switchSite(newDomain)
  206. {
  207. dbg && console.info(`BetterYTM: Switching from domain '${getDomain()}' to '${newDomain}'`);
  208. try
  209. {
  210. let subdomain;
  211. if(newDomain === "ytm")
  212. subdomain = "music";
  213. else if(newDomain === "yt")
  214. subdomain = "www";
  215. if(!subdomain)
  216. throw new TypeError(`Unrecognized domain '${newDomain}'`);
  217. const { pathname, search, hash } = new URL(location.href);
  218. const vt = getVideoTime() ?? 0;
  219. dbg && console.info(`BetterYTM: Found video time of ${vt} seconds`);
  220. const newSearch = search.includes("?") ? `${search}&t=${vt}` : `?t=${vt}`;
  221. const url = `https://${subdomain}.youtube.com${pathname}${newSearch}${hash}`;
  222. console.info(`BetterYTM - switching to domain '${newDomain}' at ${url}`);
  223. location.href = url;
  224. }
  225. catch(err)
  226. {
  227. console.error(`BetterYTM: Error while switching site:`, err);
  228. }
  229. }
  230. //#SECTION remove upgrade tab
  231. let removeUpgradeTries = 0;
  232. /**
  233. * Removes the "Upgrade" / YT Music Premium tab from the title / nav bar
  234. */
  235. function removeUpgradeTab()
  236. {
  237. const tabElem = document.querySelector(`.ytmusic-nav-bar ytmusic-pivot-bar-item-renderer[tab-id="SPunlimited"]`);
  238. if(tabElem)
  239. {
  240. tabElem.remove();
  241. dbg && console.info(`BetterYTM: Removed upgrade tab after ${removeUpgradeTries} tries`);
  242. }
  243. else if(removeUpgradeTries < triesLimit)
  244. {
  245. setTimeout(removeUpgradeTab, 250); // TODO: improve this
  246. removeUpgradeTries++;
  247. }
  248. else
  249. console.error(`BetterYTM: Couldn't find upgrade tab to remove after ${removeUpgradeTries} tries`);
  250. }
  251. //#SECTION add watermark
  252. /**
  253. * Adds a watermark beneath the logo
  254. */
  255. function addWatermark()
  256. {
  257. const watermark = document.createElement("a");
  258. watermark.id = "betterytm-watermark";
  259. watermark.className = "style-scope ytmusic-nav-bar";
  260. watermark.innerText = info.name;
  261. watermark.title = `${info.name} v${info.version}`;
  262. watermark.href = info.namespace;
  263. watermark.target = "_blank";
  264. watermark.rel = "noopener noreferrer";
  265. const style = `\
  266. #betterytm-watermark {
  267. display: inline-block;
  268. position: absolute;
  269. left: 45px;
  270. top: 43px;
  271. z-index: 10;
  272. color: white;
  273. text-decoration: none;
  274. cursor: pointer;
  275. }
  276. @media(max-width: 615px) {
  277. #betterytm-watermark {
  278. display: none;
  279. }
  280. }
  281. #betterytm-watermark:hover {
  282. text-decoration: underline;
  283. }`;
  284. addGlobalStyle(style, "watermark");
  285. const logoElem = document.querySelector("#left-content");
  286. insertAfter(logoElem, watermark);
  287. dbg && console.info(`BetterYTM: Added watermark element:`, watermark);
  288. }
  289. //#SECTION genius.com lyrics button
  290. let currentSongTitle = "";
  291. let lyricsButtonAddTries = 0;
  292. /**
  293. * Adds a genius.com lyrics button to the media controls bar
  294. */
  295. function addGeniusButton()
  296. {
  297. const likeContainer = document.querySelector(".middle-controls-buttons ytmusic-like-button-renderer#like-button-renderer");
  298. if(!likeContainer)
  299. {
  300. lyricsButtonAddTries++;
  301. if(lyricsButtonAddTries < triesLimit)
  302. return setTimeout(addGeniusButton, 250); // TODO: improve this
  303. return console.error(`BetterYTM: Couldn't find like buttons to append lyrics button to after ${lyricsButtonAddTries} tries`);
  304. }
  305. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  306. const gUrl = getGeniusUrl();
  307. const linkElem = document.createElement("a");
  308. linkElem.id = "betterytm-lyrics-button";
  309. linkElem.className = "ytmusic-player-bar";
  310. linkElem.title = "Search for lyrics on genius.com";
  311. linkElem.href = gUrl;
  312. linkElem.target = "_blank";
  313. linkElem.rel = "noopener noreferrer";
  314. linkElem.style.visibility = gUrl ? "initial" : "hidden";
  315. const style = `\
  316. #betterytm-lyrics-button {
  317. display: inline-flex;
  318. align-items: center;
  319. justify-content: center;
  320. position: relative;
  321. vertical-align: middle;
  322. margin-left: 8px;
  323. width: 40px;
  324. height: 40px;
  325. border-radius: 100%;
  326. background-color: transparent;
  327. }
  328. #betterytm-lyrics-button:hover {
  329. background-color: #383838;
  330. }
  331. #betterytm-lyrics-img {
  332. display: inline-block;
  333. z-index: 10;
  334. width: 24px;
  335. height: 24px;
  336. padding: 5px;
  337. }`;
  338. addGlobalStyle(style, "lyrics");
  339. const imgElem = document.createElement("img");
  340. imgElem.id = "betterytm-lyrics-img";
  341. imgElem.src = "https://raw.githubusercontent.com/Sv443/BetterYTM/main/resources/external/genius.png";
  342. linkElem.appendChild(imgElem);
  343. dbg && console.info(`BetterYTM: Inserted genius button after ${lyricsButtonAddTries} tries:`, linkElem);
  344. insertAfter(likeContainer, linkElem);
  345. currentSongTitle = songTitleElem.title;
  346. /** @param {MutationRecord[]} mutations */
  347. const onMutation = (mutations) => {
  348. mutations.forEach(mut => {
  349. const newTitle = mut.target.title;
  350. if(newTitle != currentSongTitle)
  351. {
  352. dbg && console.info(`BetterYTM: Song title changed from '${currentSongTitle}' to '${newTitle}'`);
  353. currentSongTitle = newTitle;
  354. const lyricsBtn = document.querySelector("#betterytm-lyrics-button");
  355. lyricsBtn.href = getGeniusUrl();
  356. lyricsBtn.style.visibility = "initial";
  357. }
  358. });
  359. };
  360. // since YT and YTM don't reload the page on video change, MutationObserver needs to be used
  361. const obs = new MutationObserver(onMutation);
  362. obs.observe(songTitleElem, { attributes: true, attributeFilter: [ "title" ] });
  363. }
  364. /**
  365. * Returns the genius.com search URL for the current song
  366. * @returns {string|null}
  367. */
  368. function getGeniusUrl()
  369. {
  370. try
  371. {
  372. const songTitleElem = document.querySelector(".content-info-wrapper > yt-formatted-string");
  373. const songMetaElem = document.querySelector("span.subtitle > yt-formatted-string:first-child");
  374. if(!songTitleElem || !songMetaElem || !songTitleElem.title)
  375. return null;
  376. const sanitizeSongName = (songName) => {
  377. let sanitized;
  378. if(songName.match(/\(|feat|ft/gmi))
  379. {
  380. // should hopefully trim right after the song name
  381. sanitized = songName.substring(0, songName.indexOf("("));
  382. }
  383. return (sanitized || songName).trim();
  384. };
  385. /** @param {string} songMeta */
  386. const splitArtist = (songMeta) => {
  387. songMeta = songMeta.split(/\s*\u2022\s*/gmiu)[0]; // split at &bull; (•) character
  388. if(songMeta.match(/&/))
  389. songMeta = songMeta.split(/\s*&\s*/gm)[0];
  390. if(songMeta.match(/,/))
  391. songMeta = songMeta.split(/,\s*/gm)[0];
  392. return songMeta;
  393. }
  394. const songNameRaw = songTitleElem.title;
  395. const songName = sanitizeSongName(songNameRaw);
  396. const artistName = splitArtist(songMetaElem.title);
  397. // TODO: artist might need further splitting before comma or ampersand
  398. const sn = encodeURIComponent(songName);
  399. const an = encodeURIComponent(artistName);
  400. /** Autoclick URL params */
  401. const acParams = features.geniusAutoclickBestResult ? `&bytm-ac-sn=${sn}&bytm-ac-an=${an}` : "";
  402. const url = `https://genius.com/search?q=${sn}%20${an}${acParams}`;
  403. dbg && console.info(`BetterYTM: Resolved genius.com URL for song '${songName}' by '${artistName}': ${url}`);
  404. return url;
  405. }
  406. catch(err)
  407. {
  408. console.error(`BetterYTM: Couldn't resolve genius.com URL:`, err);
  409. }
  410. }
  411. //#SECTION autoclick best genius.com result
  412. /**
  413. * Automatically clicks the best matching result in a genius.com search
  414. */
  415. function autoclickGeniusResult()
  416. {
  417. if(!location.pathname.includes("/search"))
  418. return;
  419. const miniCards = document.querySelectorAll(".mini_card-title_and_subtitle");
  420. if(!miniCards || miniCards.length == 0)
  421. {
  422. if(geniusAutoclickTries < Math.round(triesLimit * 2.5)) // tries limit higher due to lower timeout
  423. {
  424. geniusAutoclickTries++;
  425. return setTimeout(autoclickGeniusResult, 100); // TODO: improve this
  426. }
  427. else
  428. return console.error(`BetterYTM: Couldn't find result minicards after ${geniusAutoclickTries} tries`);
  429. }
  430. const params = getGeniusAcParams();
  431. if(!params)
  432. return console.info("BetterYTM: No query params present, not autoclicking");
  433. const { songName, artistName } = params;
  434. const resultNode = findMatchingGeniusResult(songName, artistName);
  435. if(!resultNode)
  436. return console.error("BetterYTM: Couldn't find matching result node");
  437. if(features.visualizeBestResult)
  438. {
  439. const grandpaNode = resultNode.parentElement.parentElement;
  440. grandpaNode.style.border = "2px dashed yellow";
  441. grandpaNode.style.borderRadius = "7px";
  442. grandpaNode.style.padding = "7px";
  443. }
  444. dbg && console.info(`BetterYTM: Found matching result node after ${geniusAutoclickTries} tries:`, resultNode);
  445. resultNode.click();
  446. }
  447. let geniusAutoclickTries = 0;
  448. /** @typedef {({ songName: string, artistName: string, card: Element })} SearchItem */
  449. /**
  450. * Finds a result minicard node that matches the provided song and artist names (case insensitive)
  451. * @param {string} song
  452. * @param {string} artist
  453. * @returns {Element|null}
  454. */
  455. function findMatchingGeniusResult(song, artist)
  456. {
  457. const miniCards = document.querySelectorAll(".mini_card-title_and_subtitle");
  458. dbg && console.info(`BetterYTM: Found ${miniCards.length} minicards in results, searching for match...`);
  459. /** @type {SearchItem[]} */
  460. const searchElems = [];
  461. for(const card of miniCards)
  462. {
  463. if(card.childNodes && card.childNodes.length > 0)
  464. {
  465. const title = Array.from(card.childNodes).find(cn => cn.classList && cn.classList.contains("mini_card-title"));
  466. const subTitle = Array.from(card.childNodes).find(cn => cn.classList && cn.classList.contains("mini_card-subtitle"));
  467. if(!title || !subTitle || !title.innerText || !subTitle.innerText)
  468. continue;
  469. const songName = title.innerText.toLowerCase();
  470. const artistName = subTitle.innerText.toLowerCase();
  471. searchElems.push({ songName, artistName, card });
  472. }
  473. }
  474. if(searchElems.length === 0)
  475. return null;
  476. try
  477. {
  478. const fuseOpts = {
  479. includeScore: true,
  480. isCaseSensitive: false,
  481. findAllMatches: true,
  482. threshold: 0.7,
  483. keys: [ "songName", "artistName" ],
  484. };
  485. // fuzzy search for best accuracy and reliability
  486. const fuse = new Fuse(searchElems, fuseOpts); // eslint-disable-line no-undef
  487. /** @type {({ item: SearchItem, refIndex: number, score: number })[]} */
  488. const searchResults = fuse.search(`${song} ${artist}`);
  489. if(searchResults.length > 0)
  490. {
  491. // searchResults.sort((a, b) => {
  492. // return a.score > b.score;
  493. // });
  494. console.log("Found possible results:", searchResults);
  495. return searchResults[0].item.card;
  496. }
  497. return null;
  498. }
  499. catch(err)
  500. {
  501. console.error("BetterYTM: Couldn't fuzzy search for matching result:", err);
  502. }
  503. }
  504. /**
  505. * Returns autoclick query params if they exist, else returns null
  506. * @returns {({ songName: string, artistName: string })|null}
  507. */
  508. function getGeniusAcParams()
  509. {
  510. const params = location.search.substring(1).split(/&/g);
  511. if(params.find(p => p.includes("bytm-ac-sn=")) && params.find(p => p.includes("bytm-ac-an=")))
  512. {
  513. const songName = decodeURIComponent(params.find(p => p.includes("bytm-ac-sn=")).split(/=/)[1]);
  514. const artistName = decodeURIComponent(params.find(p => p.includes("bytm-ac-an=")).split(/=/)[1]);
  515. return { songName, artistName };
  516. }
  517. return null;
  518. }
  519. //#MARKER other
  520. /**
  521. * Returns the current domain as a constant string representation
  522. * @throws {Error} If script runs on an unexpected website
  523. * @returns {Domain}
  524. */
  525. function getDomain()
  526. {
  527. const { hostname } = new URL(location.href);
  528. if(hostname.includes("music.youtube"))
  529. return "ytm";
  530. else if(hostname.includes("youtube"))
  531. return "yt";
  532. else if(hostname.includes("genius"))
  533. return "genius";
  534. else
  535. throw new Error("BetterYTM is running on an unexpected website");
  536. }
  537. /**
  538. * Returns the current video time in seconds
  539. * @returns {number|null} Returns null if the video time is unavailable
  540. */
  541. function getVideoTime()
  542. {
  543. const domain = getDomain();
  544. try
  545. {
  546. if(domain === "ytm")
  547. {
  548. const pbEl = document.querySelector("#progress-bar");
  549. return pbEl.value ?? null;
  550. }
  551. 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
  552. return 0;
  553. return null;
  554. }
  555. catch(err)
  556. {
  557. console.error("BetterYTM: Couldn't get video time due to error:", err);
  558. return null;
  559. }
  560. }
  561. /**
  562. * Inserts `afterNode` as a sibling just after the provided `beforeNode`
  563. * @param {HTMLElement} beforeNode
  564. * @param {HTMLElement} afterNode
  565. * @returns {HTMLElement} Returns the `afterNode`
  566. */
  567. function insertAfter(beforeNode, afterNode)
  568. {
  569. beforeNode.parentNode.insertBefore(afterNode, beforeNode.nextSibling);
  570. return afterNode;
  571. }
  572. /**
  573. * Adds global CSS style through a &lt;style&gt; element in the document's &lt;head&gt;
  574. * @param {string} style CSS string
  575. * @param {string} ref Reference name that is included in the &lt;style&gt;'s ID
  576. */
  577. function addGlobalStyle(style, ref)
  578. {
  579. const styleElem = document.createElement("style");
  580. styleElem.id = `betterytm-${ref}-style`;
  581. if(styleElem.styleSheet)
  582. styleElem.styleSheet.cssText = style;
  583. else
  584. styleElem.appendChild(document.createTextNode(style));
  585. document.querySelector("head").appendChild(styleElem);
  586. dbg && console.info(`BetterYTM: Inserted global style with ref '${ref}':`, styleElem);
  587. }
  588. /**
  589. * Loads a feature configuration saved persistently, returns an empty object if no feature configuration was saved
  590. * @returns {Promise<Readonly<typeof defaultFeatures | {}>>}
  591. */
  592. async function loadFeatureConf()
  593. {
  594. /** @type {string} */
  595. const featureConf = await GM.getValue("bytm-featureconf"); // eslint-disable-line no-undef
  596. return Object.freeze(featureConf ? JSON.parse(featureConf) : {});
  597. }
  598. /**
  599. * Saves a feature configuration saved persistently
  600. * @param {typeof defaultFeatures} featureConf
  601. * @returns {Promise<void>}
  602. */
  603. function saveFeatureConf(featureConf)
  604. {
  605. if(!featureConf || typeof featureConf != "object")
  606. throw new TypeError("Feature config not provided or invalid");
  607. return GM.setValue("bytm-featureconf", JSON.stringify(featureConf)); // eslint-disable-line no-undef
  608. }
  609. init(); // call init() when script is loaded
  610. })();