BetterYTM.user.js 22 KB

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