BetterYTM.user.js 22 KB

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