Restore YouTube Username from Handle to Custom

将 YouTube 用户名从 Handle 恢复为自定义名称

当前为 2024-02-23 提交的版本,查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2023 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name Restore YouTube Username from Handle to Custom
  28. // @namespace http://tampermonkey.net/
  29. // @version 0.10.3
  30. // @license MIT License
  31.  
  32. // @author CY Fung
  33. // @match https://www.youtube.com/*
  34. // @match https://m.youtube.com/*
  35. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  36. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/general-icon.png
  37. // @supportURL https://github.com/cyfung1031/userscript-supports
  38. // @run-at document-start
  39. // @grant none
  40. // @unwrap
  41. // @allFrames true
  42. // @inject-into page
  43.  
  44. // @compatible firefox Violentmonkey
  45. // @compatible firefox Tampermonkey
  46. // @compatible firefox Firemonkey
  47. // @compatible chrome Violentmonkey
  48. // @compatible chrome Tampermonkey
  49. // @compatible opera Violentmonkey
  50. // @compatible opera Tampermonkey
  51. // @compatible safari Stay
  52. // @compatible edge Violentmonkey
  53. // @compatible edge Tampermonkey
  54. // @compatible brave Violentmonkey
  55. // @compatible brave Tampermonkey
  56.  
  57. // @description To restore YouTube Username to the traditional custom name
  58. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  59. // @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
  60. // @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
  61.  
  62. // @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
  63. // @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
  64. // @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
  65. // @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
  66. // @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
  67. // @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
  68. // @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
  69. // @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
  70. // @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
  71. // @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
  72. // @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
  73. // @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
  74. // @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
  75. // @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
  76. // @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
  77. // @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
  78. // @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
  79. // @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
  80. // @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
  81. // @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
  82. // @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
  83. // @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
  84. // @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
  85. // @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
  86. // @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
  87. // @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
  88. // @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
  89. // @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
  90. // @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
  91. // @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
  92. // @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
  93. // @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
  94. // @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
  95. // @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
  96. // @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
  97. // @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
  98. // @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
  99. // @description:tr Özel İsme Kullanıcı Adını İade Etme
  100. // @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
  101. // @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
  102. // @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
  103. // @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
  104. // @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
  105. // @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
  106. // @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
  107. // @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
  108. // @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
  109. // @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
  110. // @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
  111. // @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
  112. // @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
  113. // @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
  114. // @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
  115. // @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
  116. // @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
  117. // @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
  118. // @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
  119. // @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
  120. // @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
  121. // @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్‌కు పునరుద్ధరించండి
  122. // @description:kn ಹ್ಯಾಂಡಲ್‌ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
  123. // @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
  124. // @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
  125. // @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
  126. // @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
  127. // @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
  128. // @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
  129. // @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
  130. // @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
  131.  
  132. // ==/UserScript==
  133.  
  134. /* jshint esversion:8 */
  135.  
  136. /**
  137. @typedef {string} HandleText
  138. * \@[-_a-zA-Z0-9.]{3,30}
  139. */
  140.  
  141. /**
  142. @typedef {string} ChannelId
  143. * UC[-_a-zA-Z0-9+=.]{22}
  144. * https://support.google.com/youtube/answer/6070344?hl=en
  145. * The channel ID is the 24 character alphanumeric string that starts with 'UC' in the channel URL.
  146. */
  147.  
  148. /**
  149. @typedef {string} DisplayName
  150. * Display Name
  151. */
  152.  
  153. /**
  154. @typedef DisplayNameResultObject
  155. @type {Object}
  156. @property {DisplayName} title
  157. @property {DisplayName} langTitle
  158. @property {ChannelId?} externalId
  159. @property {string[]} ownerUrls
  160. @property {string} channelUrl
  161. @property {string} vanityChannelUrl
  162. @property {boolean|undefined} verified123
  163. */
  164.  
  165. /**
  166. @typedef ChannelIdToHandleResult
  167. @type {Object}
  168. @property {HandleText} handleText
  169. @property {boolean} justPossible
  170. */
  171.  
  172. (function (__CONTEXT__) {
  173. 'use strict';
  174.  
  175. const USE_RSS_FETCHER = true; // might 404
  176. const USE_TIMEOUT_SIGNAL = false;
  177. const USE_CHANNEL_META = true;
  178. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  179. const USE_LANG_SPECIFIC_NAME = true;
  180. const UPDATE_PIN_NAME = true; // for USE_LANG_SPECIFIC_NAME
  181. const FIX_RTL_ISSUE = true;
  182.  
  183. /** @type {globalThis.PromiseConstructor} */
  184. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  185.  
  186. const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  187.  
  188. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  189. let controller = new AbortController();
  190. const r = controller.signal;
  191. let cid = setTimeout(() => {
  192. if (cid >= 1) {
  193. cid = 0;
  194. controller && controller.abort();
  195. controller = null;
  196. }
  197. }, timeout);
  198. r.clearTimeout = () => {
  199. if (cid >= 1) {
  200. clearTimeout(cid);
  201. cid = 0;
  202. }
  203. }
  204. return r;
  205. } : () => { };
  206.  
  207. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  208.  
  209. const fxOperator = (proto, propertyName) => {
  210. let propertyDescriptorGetter = null;
  211. try {
  212. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  213. // https://github.com/cyfung1031/userscript-supports/issues/9
  214. // .parentNode becomes DocumentFragment
  215. /**
  216. *
  217. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  218. *
  219. * e.g. ytd-comment-renderer#comment > div#body
  220. *
  221. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  222. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  223. *
  224. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  225. *
  226. * Alternative way: ytCustomElement.$.xxxxxxx
  227. *
  228. */
  229. } catch (e) { }
  230. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  231. };
  232.  
  233. const fxAPI = (proto, propertyName) => {
  234. const methodFunc = proto[propertyName];
  235. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  236. };
  237.  
  238. /** @type { (node: Node)=>Node | null } */
  239. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  240. /** @type { (node: Node)=>Node | null } */
  241. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  242. /** @type { (node: Node)=>Node | null } */
  243. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  244.  
  245. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  246. const elementQS = fxAPI(Element.prototype, 'querySelector');
  247. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  248. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  249.  
  250. /*
  251.  
  252.  
  253. init
  254.  
  255. initialdata
  256. state-progress
  257. state-responsereceived
  258. player-autonav-pause
  259. state-change
  260. state-navigateend
  261. player-initialized
  262. renderer-module-load-start
  263. video-data-change
  264. player-state-change
  265. updateui
  266. renderer-module-load-end -> channel owner DOM available
  267. player-autonav-pause
  268. updateui
  269. renderer-module-load-start
  270. updateui
  271. renderer-module-load-end
  272.  
  273.  
  274. playing
  275.  
  276. h5player.video-progress
  277. h5player.video-progress
  278. h5player.video-progress
  279. h5player.video-progress
  280. ...
  281.  
  282.  
  283.  
  284.  
  285. navigate new video
  286.  
  287. state-navigatestart
  288. state-change => channel owener DOM vanished
  289. state-progress
  290. ...
  291. h5player.player-state-change
  292. h5player.video-data-change
  293. h5player.player-state-change
  294. h5player.muted-autoplay-change
  295. h5player.volume-change
  296. h5player.video-data-change
  297. h5player.volume-change
  298. ...
  299.  
  300. state-progress
  301. ...
  302.  
  303. state-progress => channel owner DOM appear [just before state-responsereceived]
  304. state-responsereceived
  305.  
  306. video-data-change
  307. state-change
  308. state-navigateend
  309.  
  310.  
  311.  
  312.  
  313. UX interaction
  314.  
  315. user-activity
  316. player-autonav-pause
  317.  
  318.  
  319.  
  320.  
  321.  
  322. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  323.  
  324. EventTarget.prototype.dispatchEvent = function (ev) {
  325. if (ev instanceof Event) {
  326. if (ev.type === 'video-progress') { } else {
  327. console.log(ev.type, this, ev.target)
  328. if (ev.target === null) {
  329. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  330. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  331. }
  332. }
  333. }
  334. return this.uhfsE.apply(this, arguments);
  335. }
  336.  
  337.  
  338.  
  339. */
  340.  
  341. const isMobile = location.hostname === 'm.youtube.com';
  342.  
  343. const cfg = {};
  344. class Mutex {
  345.  
  346. constructor() {
  347. this.p = Promise.resolve()
  348. }
  349.  
  350. /**
  351. * @param {(lockResolve: () => void)} f
  352. */
  353. lockWith(f) {
  354. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  355. }
  356.  
  357. }
  358.  
  359. class OrderedMutex extends Mutex {
  360. constructor() {
  361. super();
  362. this.nextIndex = 0;
  363. this.arr = [];
  364. this.lockFunc = resolve => {
  365. if (this.arr.length >= 1) {
  366. let f = this.arr[0];
  367. if (typeof f === 'function') {
  368. this.arr.shift();
  369. if (this.nextIndex > 0) this.nextIndex--;
  370. f(resolve);
  371. return;
  372. } else {
  373. // reset if unknown error
  374. this.arr.length = 0;
  375. this.nextIndex = 0;
  376. }
  377. }
  378. resolve();
  379. };
  380. }
  381. /**
  382. * @param {(lockResolve: () => void)} f
  383. */
  384. add(f) {
  385. if (this.nextIndex === this.arr.length) {
  386. this.arr.push(f); this.nextIndex++;
  387. } else {
  388. this.arr.splice(this.nextIndex++, 0, f);
  389. }
  390. this.lockWith(this.lockFunc);
  391. }
  392. }
  393. // usage: run network request one by one
  394. const mutex = new OrderedMutex();
  395.  
  396. const createPipeline = () => {
  397. let pipelineMutex = Promise.resolve();
  398. const pipelineExecution = fn => {
  399. return new Promise((resolve, reject) => {
  400. pipelineMutex = pipelineMutex.then(async () => {
  401. let res;
  402. try {
  403. res = await fn();
  404. } catch (e) {
  405. console.log('error_F1', e);
  406. reject(e);
  407. }
  408. resolve(res);
  409. }).catch(console.warn);
  410. });
  411. };
  412. return pipelineExecution;
  413. };
  414.  
  415. /**
  416. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  417. * @template T */
  418.  
  419. /**
  420. * usage: cache the network result per web application instance.
  421. * @type {Map<ChannelId, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  422. const displayNameResStore = new Map();
  423.  
  424. /**
  425. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  426. * @type {WeakMap<Function, Function>} */
  427. const dataChangedFuncStore = new WeakMap();
  428.  
  429. /**
  430. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  431. * @type {Map<HandleText, AsyncOrResolvedValue<ChannelId>>} */
  432. const handleToChannelId = new Map();
  433.  
  434. /**
  435. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  436. * @type {Map<ChannelId, ChannelIdToHandleResult>} */
  437. const channelIdToHandle = new Map();
  438.  
  439. /**
  440. * usage: replace handle to lang-specific display name
  441. * @type {Map<HandleText, DisplayName>} */
  442. const langPreferredDisplayNameMap = new Map();
  443.  
  444. /**
  445. * AsyncValue
  446. * @class
  447. * @template T
  448. */
  449. class AsyncValue {
  450. constructor() {
  451. /** @type {T | null} */
  452. this.__value__ = null;
  453. /** @type {((value: any)=>void) | null} */
  454. this.__resolve__ = null;
  455. this.__promise__ = new Promise(resolve => {
  456. this.__resolve__ = resolve;
  457. });
  458. }
  459. /**
  460. *
  461. * @param {T} value
  462. */
  463. setValue(value) {
  464. const promise = this.__promise__;
  465. if (promise === null) throw 'Value has already been set.';
  466. this.__value__ = value;
  467. this.__promise__ = null;
  468. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  469. }
  470. /**
  471. *
  472. * @returns {Promise<T>}
  473. */
  474. async getValue() {
  475. const promise = this.__promise__;
  476. if (promise === null) return this.__value__;
  477. await promise; // promise become null
  478. this.__promise__ = null; // just in case
  479. this.__resolve__ = null;
  480. return this.__value__;
  481. }
  482. }
  483.  
  484. let isCSSAdded = false;
  485. const addCSSRulesIfRequired = () => {
  486. if (isCSSAdded) return;
  487. isCSSAdded = true;
  488. const style = document.createElement('style')
  489. let nonce = document.querySelector('head style[nonce]');
  490. nonce = nonce ? nonce.getAttribute('nonce') : null;
  491.  
  492. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (LTR, when mixed with LTR languages) */
  493. /* #contenteditable-root.yt-formatted-string:lang(he) */ /* Hebrew (pure) */
  494.  
  495. const cssText01_FIX_RTL_ISSUE = FIX_RTL_ISSUE ? `
  496.  
  497. /* Left-to-Right (LTR) Languages */
  498. #contenteditable-root.yt-formatted-string:lang(en) /* English */,
  499. #contenteditable-root.yt-formatted-string:lang(es) /* Spanish */,
  500. #contenteditable-root.yt-formatted-string:lang(fr) /* French */,
  501. #contenteditable-root.yt-formatted-string:lang(de) /* German */,
  502. #contenteditable-root.yt-formatted-string:lang(it) /* Italian */,
  503. #contenteditable-root.yt-formatted-string:lang(pt) /* Portuguese */,
  504. #contenteditable-root.yt-formatted-string:lang(ru) /* Russian */,
  505. #contenteditable-root.yt-formatted-string:lang(zh) /* Chinese */,
  506. #contenteditable-root.yt-formatted-string:lang(ja) /* Japanese */,
  507. #contenteditable-root.yt-formatted-string:lang(ko) /* Korean */,
  508. #contenteditable-root.yt-formatted-string:lang(nl) /* Dutch */,
  509. #contenteditable-root.yt-formatted-string:lang(sv) /* Swedish */,
  510. #contenteditable-root.yt-formatted-string:lang(fi) /* Finnish */,
  511. #contenteditable-root.yt-formatted-string:lang(da) /* Danish */,
  512. #contenteditable-root.yt-formatted-string:lang(no) /* Norwegian */,
  513. #contenteditable-root.yt-formatted-string:lang(pl) /* Polish */,
  514. #contenteditable-root.yt-formatted-string:lang(cs) /* Czech */,
  515. #contenteditable-root.yt-formatted-string:lang(sk) /* Slovak */,
  516. #contenteditable-root.yt-formatted-string:lang(hu) /* Hungarian */,
  517. #contenteditable-root.yt-formatted-string:lang(tr) /* Turkish */,
  518. #contenteditable-root.yt-formatted-string:lang(el) /* Greek */,
  519. #contenteditable-root.yt-formatted-string:lang(id) /* Indonesian */,
  520. #contenteditable-root.yt-formatted-string:lang(ms) /* Malay */,
  521. #contenteditable-root.yt-formatted-string:lang(th) /* Thai */,
  522. #contenteditable-root.yt-formatted-string:lang(vi) /* Vietnamese */
  523. {
  524. direction: ltr;
  525. }
  526.  
  527. /* Right-to-Left (RTL) Languages */
  528. #contenteditable-root.yt-formatted-string:lang(ar) /* Arabic */,
  529. #contenteditable-root.yt-formatted-string:lang(fa) /* Persian */,
  530. #contenteditable-root.yt-formatted-string:lang(ur) /* Urdu */,
  531. #contenteditable-root.yt-formatted-string:lang(dv) /* Divehi */
  532. {
  533. direction: rtl;
  534. }
  535.  
  536. ` : '';
  537. style.textContent = `
  538. ${cssText01_FIX_RTL_ISSUE}
  539. `.trim();
  540. if (nonce) style.setAttribute('nonce', nonce);
  541. document.head.appendChild(style);
  542. }
  543.  
  544. /**
  545. *
  546. * @param {DisplayNameResultObject} resultInfo
  547. * @param {string} channelId
  548. */
  549. const cacheHandleToChannel = (resultInfo, channelId) => {
  550.  
  551. const { vanityChannelUrl, ownerUrls } = resultInfo;
  552.  
  553. let handleText = urlToHandle(vanityChannelUrl || '');
  554.  
  555. if (handleText) {
  556. // match = true;
  557. } else if ((ownerUrls || 0).length >= 1) {
  558. for (const ownerUrl of ownerUrls) {
  559. handleText = urlToHandle(ownerUrl || '');
  560.  
  561. if (handleText) {
  562. // match = true;
  563. break;
  564. }
  565. }
  566. }
  567. if (handleText) {
  568.  
  569. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  570. if (asyncValue instanceof AsyncValue) {
  571. asyncValue.setValue(channelId);
  572. }
  573. handleToChannelId.set(handleText, channelId);
  574. }
  575.  
  576.  
  577. }
  578.  
  579. /**
  580. *
  581. * @param {string} channelId
  582. * @param {Function} onDownloaded
  583. * @param {Function} onResulted
  584. * @param {Function} onError
  585. */
  586. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  587.  
  588. let signal = timeoutSignal(4000);
  589.  
  590. const requestBody = {
  591. "context": {
  592. "client": {
  593. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  594. "clientName": "MWEB", // "WEB", "MWEB"
  595. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  596. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  597. "playerType": "UNIPLAYER",
  598. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  599. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  600. "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  601. "mainAppWebInfo": {
  602. "graftUrl": `/channel/${channelId}`,
  603. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  604. "isWebNativeShareAvailable": true
  605. }
  606. },
  607. "user": {
  608. "lockedSafetyMode": false
  609. },
  610. "request": {
  611. "useSsl": true,
  612. "internalExperimentFlags": [],
  613. "consistencyTokenJars": []
  614. }
  615. },
  616. "browseId": `${channelId}`
  617. };
  618.  
  619. if (USE_LANG_SPECIFIC_NAME && cfg.HL && cfg.GL) {
  620. Object.assign(requestBody.context.client, {
  621. "hl": cfg.HL,
  622. "gl": cfg.GL,
  623. });
  624. }
  625.  
  626. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  627. "method": "POST",
  628. "mode": "same-origin",
  629. "credentials": "omit",
  630.  
  631. referrerPolicy: "no-referrer",
  632. cache: "default", // no effect on POST request
  633. // cache: "force-cache",
  634. redirect: "error", // there shall be no redirection in this API request
  635. integrity: "",
  636. keepalive: false,
  637. signal,
  638.  
  639. "headers": {
  640. "Content-Type": "application/json", // content type of the body data in POST request
  641. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  642. // X-Youtube-Bootstrap-Logged-In: false,
  643. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  644. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  645.  
  646. "Accept": "application/json",
  647. },
  648. "body": JSON.stringify(requestBody)
  649. })).then(res => {
  650. signal && signal.clearTimeout && signal.clearTimeout();
  651. signal = null;
  652. onDownloaded();
  653. onDownloaded = null;
  654. return res.json();
  655. }).then(resJson => {
  656. let resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  657. let title = resultInfo.title;
  658. if (title) {
  659.  
  660. resultInfo.title = '';
  661. resultInfo.langTitle = title;
  662.  
  663. if (cfg.ownerProfileUrl && cfg.ownerChannelName && cfg.ownerChannelName !== title) {
  664. let matched = false;
  665.  
  666. const ownerProfileUrlLowerCase = cfg.ownerProfileUrl.toLowerCase();
  667. if (ownerProfileUrlLowerCase.endsWith(`/channel/${channelId.toLowerCase()}`)) matched = true;
  668. else {
  669.  
  670. for (const ownerUrl of resultInfo.ownerUrls) {
  671. if (ownerUrl.toLowerCase().endsWith(ownerProfileUrlLowerCase)) {
  672. matched = true;
  673. break;
  674. }
  675. }
  676.  
  677. }
  678.  
  679. if (matched) {
  680. resultInfo.title = cfg.ownerChannelName;
  681. }
  682. }
  683.  
  684. }
  685.  
  686. onResulted(resultInfo);
  687. onResulted = null;
  688. }).catch(onError);
  689.  
  690. };
  691.  
  692. /**
  693. *
  694. * @param {string} channelId
  695. * @param {Function} onDownloaded
  696. * @param {Function} onResulted
  697. * @param {Function} onError
  698. */
  699. let fetchRSSFailed = false;
  700. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  701.  
  702. let signal = timeoutSignal(4000);
  703. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  704. // YouTube RSS Response - public, max-age=900
  705.  
  706. "method": "GET",
  707. "mode": "same-origin",
  708. "credentials": "omit",
  709.  
  710. referrerPolicy: "no-referrer",
  711. cache: "default",
  712. // cache: "no-cache",
  713. redirect: "error", // there shall be no redirection in this API request
  714. integrity: "",
  715. keepalive: false,
  716. signal,
  717.  
  718. "headers": {
  719. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  720. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  721. // seems YouTube RSS Feeds server insists its own Cache-Control.
  722.  
  723. // "Content-Type": "text/xml; charset=UTF-8",
  724. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  725. // X-Youtube-Bootstrap-Logged-In: false,
  726. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  727. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  728.  
  729. "Accept": "text/xml",
  730. }
  731. }).then(res => {
  732.  
  733. signal && signal.clearTimeout && signal.clearTimeout();
  734. signal = null;
  735.  
  736. if (res.ok === true && res.redirected === false && res.status === 200 && res.type === "basic") {
  737.  
  738. onDownloaded();
  739. onDownloaded = null;
  740. return res.text();
  741.  
  742. }
  743. return null;
  744.  
  745. }).then(resText => {
  746. if (resText && typeof resText === 'string' && resText.includes('<feed') && !resText.includes('<!DOCTYPE')) {
  747.  
  748. } else {
  749. if (onDownloaded) {
  750.  
  751. onDownloaded();
  752. onDownloaded = null;
  753. }
  754. onResulted(-1);
  755. return;
  756.  
  757. }
  758.  
  759.  
  760. // console.log(124, , resText)
  761. let eIdx = resText.indexOf('<entry>');
  762. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  763.  
  764. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  765. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  766. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  767. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  768.  
  769.  
  770. let name, uri, mt;
  771.  
  772. // ===============================================================
  773.  
  774. /* removed in 2023.06.30 */
  775.  
  776.  
  777. // ===============================================================
  778.  
  779.  
  780. const wIdx1 = mText.indexOf('<author>');
  781. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  782.  
  783. if (wIdx1 > 0 && wIdx2 > 0) {
  784. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  785. const template = document.createElement('template');
  786. template.innerHTML = qText;
  787. /** @type {HTMLElement | null} */
  788. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  789. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  790. const nodeName = authorChild.nodeName;
  791. if (nodeName === 'NAME') name = authorChild.textContent;
  792. else if (nodeName === 'URI') {
  793. uri = authorChild.textContent;
  794. mt = obtainChannelId(uri);
  795. }
  796. }
  797. template.innerHTML = '';
  798. }
  799.  
  800. if (!name && !uri) {
  801.  
  802. // fallback
  803.  
  804. const parser = new DOMParser();
  805. const xmlDoc = parser.parseFromString(mText, "text/xml");
  806.  
  807. // const author = xmlDoc.querySelector("author");
  808.  
  809. // https://extendsclass.com/xpath-tester.html
  810.  
  811. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  812.  
  813. let authorChild;
  814. while ((authorChild = authorChilds.iterateNext()) !== null) {
  815. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  816. else if (authorChild.nodeName === 'uri') {
  817. uri = authorChild.textContent;
  818. mt = obtainChannelId(uri);
  819. }
  820. }
  821.  
  822. try {
  823. xmlDoc.firstChild.remove();
  824. } catch (e) { }
  825.  
  826. }
  827.  
  828.  
  829.  
  830.  
  831. let res = null;
  832.  
  833. if (name && uri && mt && mt === channelId) {
  834.  
  835.  
  836. let object = channelIdToHandle.get(mt);
  837.  
  838. if (object) {
  839.  
  840. const handleText = object.handleText;
  841.  
  842. if (handleText === name) channelIdToHandle.delete(mt);
  843. else {
  844. object.justPossible = false; // ignore @handle checking
  845.  
  846. res = {
  847. "title": name,
  848. "externalId": mt,
  849. "ownerUrls": [
  850. `http://www.youtube.com/${handleText}`
  851. ],
  852. "channelUrl": uri,
  853. "vanityChannelUrl": `http://www.youtube.com/${handleText}`
  854. };
  855.  
  856. if (USE_LANG_SPECIFIC_NAME) {
  857. const langPreferredDisplayName = langPreferredDisplayNameMap.get(handleText);
  858. if (langPreferredDisplayName && name !== langPreferredDisplayName) res.langTitle = langPreferredDisplayName;
  859. }
  860.  
  861. }
  862. }
  863. }
  864.  
  865. onResulted(res);
  866. onResulted = null;
  867.  
  868. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  869. // onResulted(resultInfo);
  870. }).catch(onError);
  871.  
  872.  
  873.  
  874. }
  875.  
  876. /**
  877. *
  878. * @param {string} channelId
  879. */
  880. function stackNewRequest(channelId) {
  881.  
  882. mutex.add(lockResolve => {
  883.  
  884. let bResult = displayNameResStore.get(channelId);
  885. if (!(bResult instanceof AsyncValue)) {
  886. // resolved or removed
  887. lockResolve(); lockResolve = null;
  888. return;
  889. }
  890.  
  891. let setResult = (result) => {
  892. setResult = null;
  893. if (!result) {
  894. bResult.fetchingState = 0;
  895. bResult.setValue(null);
  896. displayNameResStore.delete(channelId); // create another network response in the next request
  897. } else {
  898. bResult.fetchingState = 4;
  899. bResult.setValue(result);
  900. displayNameResStore.set(channelId, result); // update store result to resolved value
  901. }
  902. bResult = null;
  903. }
  904.  
  905. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  906. // request is already done. no need to stack any request
  907. lockResolve(); lockResolve = null;
  908. return;
  909. }
  910.  
  911. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  912. // element has already been removed
  913. lockResolve(); lockResolve = null;
  914. setResult(null);
  915. return;
  916. }
  917.  
  918. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  919.  
  920. bResult.fetchingState = 2;
  921.  
  922.  
  923. const retry = () => {
  924.  
  925. fetchRSSFailed = true;
  926.  
  927. bResult.fetchingState = 2;
  928.  
  929. // Promise.resolve(channelId).then(stackNewRequest);
  930. fetcherBrowseAPI(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  931. }
  932.  
  933. const mobj = {
  934. fetchOnDownload: () => {
  935. bResult.fetchingState = 3;
  936. },
  937. fetchOnSuccess: resultInfo => {
  938.  
  939. if (resultInfo === -1) {
  940. retry();
  941. return;
  942. }
  943.  
  944. lockResolve && lockResolve();
  945. lockResolve = null;
  946. // console.log(900)
  947.  
  948. if (!resultInfo) {
  949. // invalid json format
  950. setResult(null);
  951. return;
  952. }
  953.  
  954. cacheHandleToChannel(resultInfo, channelId);
  955.  
  956. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  957.  
  958. const displayNameRes = { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  959.  
  960. setResult(displayNameRes);
  961. },
  962. fetchOnFail: e => {
  963.  
  964.  
  965. console.warn(e);
  966. if (mobj.fetcher === fetcherRSS) {
  967. retry();
  968.  
  969. } else {
  970.  
  971. lockResolve && lockResolve();
  972. lockResolve = null;
  973. // console.warn(e);
  974. setResult && setResult(null);
  975. }
  976. }
  977. }
  978.  
  979.  
  980. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  981. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  982. mobj.fetcher = USE_RSS_FETCHER && fetcherRSS && !fetchRSSFailed && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  983. mobj.fetcher(channelId, mobj.fetchOnDownload, mobj.fetchOnSuccess, mobj.fetchOnFail);
  984.  
  985. });
  986.  
  987. }
  988.  
  989. /**
  990. *
  991. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  992. * @returns Example: _\@yr__kd_
  993. */
  994. function urlToHandle(url) {
  995.  
  996. if (typeof url !== 'string') return '';
  997. let i = url.indexOf('.youtube.com/');
  998. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  999. else if (url.charAt(0) === '/') url = url.substring(1);
  1000. return isDisplayAsHandle(url) ? url : '';
  1001.  
  1002. }
  1003.  
  1004. /**
  1005. *
  1006. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  1007. * @returns {Promise<DisplayNameResultObject | null>}
  1008. */
  1009. async function getDisplayName(channelId) {
  1010.  
  1011. let cache = displayNameResStore.get(channelId);
  1012. let isStackNewRequest = false;
  1013.  
  1014. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  1015. let aResult;
  1016.  
  1017. if (cache instanceof AsyncValue) {
  1018. aResult = cache;
  1019. if (aResult.fetchingState >= 2) {
  1020. // aResult.fetchingState
  1021. // 2: network fetch started
  1022. // 3: network fetch ended
  1023. // isStackNewRequest = false;
  1024. } else {
  1025. // 0: invalid before
  1026. // 1: scheduled but not yet fetch
  1027. isStackNewRequest = true;
  1028. }
  1029. } else if (cache) {
  1030. // resolved result
  1031. return cache;
  1032. } else {
  1033. // else no cached value found
  1034. /** @type {AsyncValue<DisplayNameResultObject>} */
  1035. aResult = new AsyncValue();
  1036. displayNameResStore.set(channelId, aResult);
  1037. isStackNewRequest = true;
  1038. }
  1039.  
  1040. if (isStackNewRequest) {
  1041. aResult.fetchingState = 1;
  1042. stackNewRequest(channelId);
  1043. }
  1044. return await aResult.getValue();
  1045. }
  1046.  
  1047.  
  1048. /**
  1049. *
  1050. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  1051. * @returns
  1052. * * Outdated?
  1053. */
  1054. const obtainChannelId = (href) => {
  1055. const s = `/${href}`;
  1056. if (s.length >= 33) {
  1057. const m = /\/channel\/(UC[-_a-zA-Z0-9+=.]{22})(\/|$)/.exec(s);
  1058. return !m ? '' : (m[1] || '');
  1059. }
  1060. return '';
  1061. };
  1062.  
  1063. const isUCBrowserId = (browseId) => {
  1064. return typeof browseId === 'string' && browseId.length === 24 && browseId.startsWith('UC') && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId);
  1065. }
  1066.  
  1067.  
  1068. /**
  1069. *
  1070. * @param {Element} ytElm
  1071. */
  1072. const resetWhenDataChanged = (ths) => {
  1073. const cnt = insp(ths);
  1074. const ytElm = cnt.hostElement instanceof Element ? cnt.hostElement : cnt instanceof Element ? cnt : ths;
  1075. if (ytElm instanceof Element) {
  1076. const anchors = elementQSA(ytElm, 'a[id][href][jkrgy]');
  1077. // const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  1078. if ((anchors || 0).length >= 1 && (insp(ytElm).data || 0).jkrgx !== 1) {
  1079. for (const anchor of anchors) {
  1080. anchor.removeAttribute('jkrgy');
  1081. }
  1082. }
  1083. }
  1084. }
  1085.  
  1086. /**
  1087. *
  1088. * @param {Function} dataChanged original dataChanged function
  1089. * @returns new dataChanged function
  1090. */
  1091. const dataChangeFuncProducer = (dataChanged) => {
  1092. /** @this HTMLElement */
  1093. return function () {
  1094. resetWhenDataChanged(this);
  1095. return dataChanged.apply(this, arguments);
  1096. }
  1097. };
  1098.  
  1099. /**
  1100. *
  1101. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  1102. * @param {string} anchorHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ (old) 2024 Feb -> /@user-abc1234
  1103. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  1104. * @returns
  1105. */
  1106. const anchorIntegrityCheck = (anchor, anchorHref) => {
  1107.  
  1108. let currentHref = anchor.getAttribute('href');
  1109. if (currentHref === anchorHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  1110.  
  1111. return (currentHref + '/').indexOf(anchorHref + '/') >= 0;
  1112.  
  1113. };
  1114.  
  1115. /**
  1116. *
  1117. * @param {string} currentDisplayed
  1118. * @param {DisplayNameResultObject} fetchResult
  1119. * @returns
  1120. */
  1121. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  1122.  
  1123. const { title, langTitle, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  1124.  
  1125. const currentDisplayTrimmed = currentDisplayed.trim(); // @IORIMATSUNAGA
  1126. const currentDisplayTrimmedLowerCase = currentDisplayTrimmed.toLowerCase(); // @iorimatsunaga
  1127. let match = false;
  1128. if (verified123) {
  1129. match = true;
  1130. } else if ((vanityChannelUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmedLowerCase}`)) {
  1131. match = true;
  1132. } else if ((ownerUrls || 0).length >= 1) {
  1133. for (const ownerUrl of ownerUrls) {
  1134. if ((ownerUrl || '').toLowerCase().endsWith(`/${currentDisplayTrimmed}`)) {
  1135. match = true;
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. if (match) {
  1141. return currentDisplayTrimmed;
  1142. }
  1143. return '';
  1144.  
  1145. };
  1146.  
  1147. /**
  1148. *
  1149. *
  1150.  
  1151. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  1152.  
  1153. - Is between 3-30 characters
  1154. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  1155. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  1156. - Is not URL-like or phone number-like
  1157. - Is not already being used
  1158. - Follows YouTube's Community Guidelines
  1159.  
  1160. ### Handle automatically generated by YouTube
  1161. - `@user-XXXX`
  1162. - without dot (.)
  1163. *
  1164. * @param {string} text
  1165. * @returns
  1166. */
  1167. const isDisplayAsHandle = (text) => {
  1168.  
  1169. if (typeof text !== 'string') return false;
  1170. if (text.length < 4) return false;
  1171. if (text.indexOf('@') < 0) return false;
  1172. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  1173.  
  1174. };
  1175.  
  1176. /**
  1177. *
  1178. * @param {Object[]} contentTexts
  1179. * @param {number} idx
  1180. * @returns
  1181. */
  1182. const contentTextProcess = (contentTexts, idx) => {
  1183. const contentText = contentTexts[idx];
  1184. const text = (contentText || 0).text;
  1185. const browseId = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1186. const canonicalBaseUrl = ((contentText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1187. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1188. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1189.  
  1190. if (!isDisplayAsHandle(text)) return null;
  1191. const channelId = browseId;
  1192.  
  1193. return getDisplayName(channelId).then(fetchResult => {
  1194. let resolveResult = null;
  1195. if (fetchResult) {
  1196. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1197.  
  1198. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1199. if (textTrimmed) {
  1200. resolveResult = (md) => {
  1201. let runs = ((md || 0).contentText || 0).runs;
  1202. if (!runs || !runs[idx]) return;
  1203. if (runs[idx].text !== text) return;
  1204. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1205. md.contentText = Object.assign({}, md.contentText);
  1206. };
  1207. }
  1208. }
  1209. return resolveResult; // function as a Promise
  1210. });
  1211. }
  1212.  
  1213. return null;
  1214. };
  1215.  
  1216. const editableTextProcess = (editableTexts, idx) => {
  1217. const editableText = editableTexts[idx];
  1218. const text = (editableText || 0).text;
  1219.  
  1220. const browseId = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).browseId || '';
  1221. const canonicalBaseUrl = ((editableText.navigationEndpoint || 0).browseEndpoint || 0).canonicalBaseUrl || ''; // TBC
  1222. const url = (((editableText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url; // TBC
  1223. if (typeof url === 'string' && typeof text === 'string' && typeof browseId === 'string' && browseId && isUCBrowserId(browseId)) {
  1224.  
  1225. if (!isDisplayAsHandle(text)) return null;
  1226. const channelId = browseId;
  1227.  
  1228. return getDisplayName(channelId).then(fetchResult => {
  1229. let resolveResult = null;
  1230. if (fetchResult) {
  1231. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  1232.  
  1233. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  1234. if (textTrimmed) {
  1235. resolveResult = (md) => {
  1236. let commentReplyDialogRenderer = null;
  1237. try {
  1238. commentReplyDialogRenderer = md.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  1239. } catch (e) { }
  1240. if (!commentReplyDialogRenderer) return;
  1241. const editableText = commentReplyDialogRenderer.editableText || 0;
  1242.  
  1243. let runs = (editableText || 0).runs;
  1244. if (!runs || !runs[idx]) return;
  1245. if (runs[idx].text !== text) return;
  1246. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  1247. commentReplyDialogRenderer.editableText = Object.assign({}, commentReplyDialogRenderer.editableText);
  1248. };
  1249. }
  1250. }
  1251. return resolveResult; // function as a Promise
  1252. });
  1253. }
  1254.  
  1255. return null;
  1256. };
  1257.  
  1258. /**
  1259. *
  1260. * @param {ParentNode} parentNode
  1261. * @param {Function} callback
  1262. */
  1263. function findTextNodes(parentNode, callback) {
  1264. /**
  1265. *
  1266. * @param {Node} node
  1267. * @returns
  1268. */
  1269. function traverse(node) {
  1270. if (node.nodeType === Node.TEXT_NODE) {
  1271. let r = callback(node);
  1272. if (r === true) return true;
  1273. }
  1274.  
  1275. let childNode = nodeFirstChild(node);
  1276. while (childNode) {
  1277. let r = traverse(childNode);
  1278. if (r === true) return true;
  1279. childNode = nodeNextSibling(childNode);
  1280. }
  1281. }
  1282.  
  1283. traverse(parentNode);
  1284. }
  1285.  
  1286. function updatePinnedCommentBadge(md, title, langTitle) {
  1287.  
  1288.  
  1289. let setPinnedCommentBadge = false;
  1290. if (((((md.pinnedCommentBadge || 0).pinnedCommentBadgeRenderer || 0).label || 0).runs || 0).length === 2) {
  1291. setPinnedCommentBadge = true;
  1292. }
  1293. if (setPinnedCommentBadge) {
  1294. let idx = 0;
  1295. let jdx = -1;
  1296. for (const textRun of md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs) {
  1297. if (textRun.text === title) {
  1298. jdx = idx;
  1299. break;
  1300. }
  1301. idx++;
  1302. }
  1303. if (jdx >= 0) {
  1304. const runs = md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label.runs.slice(0);
  1305. runs[jdx] = Object.assign({}, runs[jdx], { text: langTitle });
  1306. md.pinnedCommentBadge = Object.assign({}, md.pinnedCommentBadge);
  1307. md.pinnedCommentBadge.pinnedCommentBadgeRenderer = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer);
  1308. md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label = Object.assign({}, md.pinnedCommentBadge.pinnedCommentBadgeRenderer.label, { runs });
  1309. }
  1310. }
  1311.  
  1312. }
  1313.  
  1314. /**
  1315. *
  1316. * @param {ParentNode} parentNode
  1317. * @param {Object[]} contentTexts
  1318. * @param {number} aidx
  1319. * @returns
  1320. */
  1321. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  1322.  
  1323.  
  1324. let commentText = elementQS(parentNode, '.comment-text');
  1325. if (!commentText) return;
  1326. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  1327. let currentText = commentText.textContent;
  1328. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  1329. if (!textMatch) return;
  1330.  
  1331. const contentText = contentTexts[aidx];
  1332.  
  1333. /** @type {string} */
  1334. const handleText = contentText.text.trim();
  1335. /** @type {string | null | undefined} */
  1336. let channelId;
  1337.  
  1338. let cache = handleToChannelId.get(handleText);
  1339.  
  1340. if (typeof cache === 'string') {
  1341. channelId = cache;
  1342. } else if (cache instanceof AsyncValue) {
  1343. channelId = await cache.getValue();
  1344. } else {
  1345. /** @type {AsyncValue<string>} */
  1346. const asyncValue = new AsyncValue();
  1347. handleToChannelId.set(handleText, asyncValue);
  1348. channelId = await asyncValue.getValue(); // note: it could be never resolved
  1349. }
  1350.  
  1351. if (!channelId) return; // just in case
  1352.  
  1353. if (commentText.isConnected !== true) return; // already removed
  1354. if (commentText.textContent !== currentText) return; // already changed
  1355.  
  1356. const fetchResult = await getDisplayName(channelId);
  1357.  
  1358. if (fetchResult === null) return;
  1359.  
  1360. const { title, langTitle, externalId } = fetchResult;
  1361. const titleForDisplay = langTitle || title;
  1362. if (externalId !== channelId) return; // channel id must be the same
  1363.  
  1364. if (commentText.isConnected !== true) return; // already removed
  1365. if (commentText.textContent !== currentText) return; // already changed
  1366.  
  1367. let search = contentText.text;
  1368. if (typeof search === 'string') {
  1369.  
  1370. const searchTrimmed = search.trim();
  1371. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1372. contentText.text = search.replace(searchTrimmed, "@" + titleForDisplay); // mention
  1373.  
  1374. findTextNodes(commentText, (textnode) => {
  1375. if (textnode.nodeValue.indexOf(search) >= 0) {
  1376. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1377. return true;
  1378. }
  1379. });
  1380. }
  1381.  
  1382. }
  1383.  
  1384. }
  1385.  
  1386. /**
  1387. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1388. * @type { (anchor: HTMLElement, anchorHref: string?, mt: string?) => Promise<void> }
  1389. */
  1390.  
  1391. const getDisplayTextDOMForCommentRenderer = (root) => { // mobile
  1392. let displayTextDOM = elementQS(root, '.comment-header .comment-title');
  1393. if (displayTextDOM) {
  1394. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1395. }
  1396. return displayTextDOM;
  1397. }
  1398.  
  1399. const domCheckAsync = isMobile ? async (anchor, anchorHref, mt) => {
  1400.  
  1401. try {
  1402. if (!anchorHref || !mt) return;
  1403. let parentNode = nodeParent(anchor);
  1404. while (parentNode instanceof Node) {
  1405. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1406. parentNode = nodeParent(parentNode);
  1407. }
  1408. if (parentNode instanceof Node) { } else return;
  1409.  
  1410. const displayTextDOM = getDisplayTextDOMForCommentRenderer(parentNode);
  1411. const airaLabel = anchor.getAttribute('aria-label');
  1412.  
  1413. const kHrefValue = anchor.getAttribute('href'); // guess (Feb 2024)
  1414. if (displayTextDOM && (airaLabel || (kHrefValue.startsWith('/@') && /^\/@[-_a-zA-Z0-9.]{3,30}$/.test(kHrefValue)))) {
  1415.  
  1416. const kHrefHandle = kHrefValue.substring(1); // guess (Feb 2024)
  1417. const kHandlerText = airaLabel ? airaLabel.trim() : kHrefHandle; // guess
  1418. const kNodeText = airaLabel ? airaLabel : kHrefHandle;
  1419.  
  1420. const parentNodeData = insp(parentNode).data;
  1421. const runs = ((parentNodeData || 0).authorText || 0).runs;
  1422.  
  1423. if (displayTextDOM.textContent.trim() === kHandlerText && isDisplayAsHandle(kNodeText) && runs && (runs[0] || 0).text === kNodeText) {
  1424.  
  1425. if (!channelIdToHandle.has(mt)) {
  1426. channelIdToHandle.set(mt, {
  1427. handleText: kHandlerText,
  1428. justPossible: true
  1429. });
  1430. }
  1431.  
  1432. const fetchResult = await getDisplayName(mt);
  1433.  
  1434. if (fetchResult === null) return;
  1435.  
  1436. const { title, langTitle, externalId } = fetchResult;
  1437. const titleForDisplay = langTitle || title;
  1438. if (externalId !== mt) return; // channel id must be the same
  1439.  
  1440. // anchor href might be changed by external
  1441. if (!anchorIntegrityCheck(anchor, anchorHref)) return;
  1442.  
  1443. if (displayTextDOM.isConnected !== true) return; // already removed
  1444.  
  1445. let found = false;
  1446.  
  1447. findTextNodes(displayTextDOM, (textnode) => {
  1448. if (textnode.nodeValue === kNodeText) {
  1449. textnode.nodeValue = titleForDisplay;
  1450. found = true;
  1451. return true;
  1452. }
  1453. });
  1454.  
  1455. if (!found) return;
  1456. if (airaLabel) anchor.setAttribute('aria-label', titleForDisplay);
  1457. runs[0].text = titleForDisplay;
  1458.  
  1459. if (UPDATE_PIN_NAME && title && langTitle && langTitle !== title) {
  1460. const renderer = HTMLElement.prototype.closest.call(anchor, 'ytm-comment-renderer');
  1461. const pinned = !renderer ? null : HTMLElement.prototype.querySelector.call(renderer, 'ytm-pinned-comment-badge-renderer');
  1462. const spanText = !pinned ? null : HTMLElement.prototype.querySelector.call(pinned, 'span.yt-core-attributed-string[role="text"]');
  1463. const tc = spanText ? spanText.textContent : '';
  1464. updatePinnedCommentBadge(parentNodeData, title, langTitle);
  1465. if (tc && tc === spanText.textContent) {
  1466. let idx = tc.indexOf(title);
  1467. if (idx >= 0) {
  1468. spanText.textContent = tc.substring(0, idx) + langTitle + tc.substring(idx + title.length);
  1469. }
  1470. }
  1471. }
  1472.  
  1473. const contentTexts = (parentNodeData.contentText || 0).runs;
  1474. if (contentTexts && contentTexts.length >= 2) {
  1475. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1476. const contentText = contentTexts[aidx] || 0;
  1477. if (contentText.italics !== true) {
  1478. let isHandle = isDisplayAsHandle(contentText.text);
  1479. if (isHandle) {
  1480. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1481. }
  1482. }
  1483. }
  1484. }
  1485.  
  1486. }
  1487. }
  1488.  
  1489. } catch (e) {
  1490. console.warn(e);
  1491. }
  1492.  
  1493. } : async (anchor, anchorHref, mt) => {
  1494.  
  1495. try {
  1496. if (!anchorHref || !mt) return;
  1497. let parentNode = nodeParent(anchor);
  1498. while (parentNode instanceof Node) {
  1499. const cnt = insp(parentNode);
  1500. if (typeof cnt.is === 'string' && typeof cnt.dataChanged === 'function') break;
  1501. parentNode = nodeParent(parentNode);
  1502. }
  1503. if (parentNode instanceof Node) { } else return;
  1504. const parentNodeController = insp(parentNode);
  1505. const authorText = (parentNodeController.data || 0).authorText;
  1506. const currentDisplayed = (authorText || 0).simpleText;
  1507. if (typeof currentDisplayed !== 'string') return;
  1508. if (!isDisplayAsHandle(currentDisplayed)) return;
  1509.  
  1510. if (!channelIdToHandle.has(mt)) {
  1511. channelIdToHandle.set(mt, {
  1512. handleText: currentDisplayed.trim(),
  1513. justPossible: true
  1514. });
  1515. }
  1516.  
  1517. let oldDataChangedFn = parentNodeController.dataChanged;
  1518. if (typeof oldDataChangedFn === 'function' && !oldDataChangedFn.jkrgx) {
  1519. let newDataChangedFn = dataChangedFuncStore.get(oldDataChangedFn);
  1520. if (!newDataChangedFn) {
  1521. newDataChangedFn = dataChangeFuncProducer(oldDataChangedFn);
  1522. newDataChangedFn.jkrgx = 1;
  1523. dataChangedFuncStore.set(oldDataChangedFn, newDataChangedFn);
  1524. }
  1525. parentNodeController.dataChanged = newDataChangedFn;
  1526. }
  1527.  
  1528. oldDataChangedFn = parentNodeController.hostElement.dataChanged;
  1529. if (typeof oldDataChangedFn === 'function' && !oldDataChangedFn.jkrgx) {
  1530. let newDataChangedFn = dataChangedFuncStore.get(oldDataChangedFn);
  1531. if (!newDataChangedFn) {
  1532. newDataChangedFn = dataChangeFuncProducer(oldDataChangedFn);
  1533. newDataChangedFn.jkrgx = 1;
  1534. dataChangedFuncStore.set(oldDataChangedFn, newDataChangedFn);
  1535. }
  1536. parentNodeController.hostElement.dataChanged = newDataChangedFn;
  1537. }
  1538.  
  1539. const fetchResult = await getDisplayName(mt);
  1540.  
  1541. if (fetchResult === null) return;
  1542.  
  1543. const { title, langTitle, externalId } = fetchResult;
  1544. const titleForDisplay = langTitle || title;
  1545. if (externalId !== mt) return; // channel id must be the same
  1546.  
  1547. // anchor href might be changed by external
  1548. if (!anchorIntegrityCheck(anchor, anchorHref)) return;
  1549.  
  1550. const parentNodeData = parentNodeController.data;
  1551. const funcPromises = [];
  1552.  
  1553. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1554.  
  1555. if (authorText.simpleText !== currentDisplayed) return;
  1556. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1557. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  1558. if (currentDisplayTrimmed && currentDisplayed !== titleForDisplay && cSimpleText === currentDisplayed) {
  1559.  
  1560. // the inside hyperlinks will be only converted if its parent author name is handle
  1561. const contentTexts = (parentNodeData.contentText || 0).runs;
  1562. if (contentTexts && contentTexts.length >= 1) {
  1563. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1564. const r = contentTextProcess(contentTexts, aidx);
  1565. if (r instanceof Promise) funcPromises.push(r);
  1566. }
  1567. }
  1568.  
  1569. const md = Object.assign({}, parentNodeData);
  1570. let setBadge = false;
  1571. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  1572. setBadge = true;
  1573. }
  1574. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1575. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, titleForDisplay) });
  1576. if (setBadge) {
  1577. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  1578. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  1579. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: titleForDisplay });
  1580.  
  1581. }
  1582.  
  1583. let setReplyEditableText = false;
  1584. if (((((((((parentNodeData.actionButtons || 0).commentActionButtonsRenderer || 0).replyButton || 0).buttonRenderer || 0).navigationEndpoint || 0).createCommentReplyDialogEndpoint || 0).dialog || 0).commentReplyDialogRenderer || 0).editableText) {
  1585. setReplyEditableText = true;
  1586. }
  1587. if (setReplyEditableText) {
  1588. const commentReplyDialogRenderer = parentNodeData.actionButtons.commentActionButtonsRenderer.replyButton.buttonRenderer.navigationEndpoint.createCommentReplyDialogEndpoint.dialog.commentReplyDialogRenderer;
  1589. const editableText = commentReplyDialogRenderer.editableText;
  1590. const editableTexts = editableText.runs;
  1591. if (editableTexts && editableTexts.length >= 1) {
  1592. for (let aidx = 0; aidx < editableTexts.length; aidx++) {
  1593. const r = editableTextProcess(editableTexts, aidx);
  1594. if (r instanceof Promise) funcPromises.push(r);
  1595. }
  1596. }
  1597. }
  1598.  
  1599. if (UPDATE_PIN_NAME) {
  1600. updatePinnedCommentBadge(md, title, langTitle);
  1601. }
  1602.  
  1603. if (funcPromises.length >= 1) {
  1604. let funcs = await Promise.all(funcPromises);
  1605.  
  1606. for (const func of funcs) {
  1607. if (typeof func === 'function') {
  1608. func(md);
  1609. }
  1610. }
  1611. }
  1612.  
  1613. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1614. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  1615. addCSSRulesIfRequired();
  1616. }
  1617.  
  1618.  
  1619. }
  1620.  
  1621. }
  1622. } catch (e) {
  1623. console.warn(e);
  1624. }
  1625.  
  1626. }
  1627.  
  1628. /**
  1629. *
  1630. * @param {string} url
  1631. * @returns
  1632. */
  1633. const channelUrlUnify = (url) => {
  1634.  
  1635. if (typeof url !== 'string') return url; // type unchanged
  1636. let c0 = url.charAt(0);
  1637. if (c0 === '/') return url;
  1638. let i = url.indexOf('.youtube.com/');
  1639. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1640. else if (url.charAt(0) !== '/') url = '/' + url;
  1641. return url
  1642.  
  1643. }
  1644.  
  1645. const parentYtElement = (node, nodeName, maxN) => {
  1646. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  1647. if (pDom.nodeName === nodeName) {
  1648. return pDom;
  1649. }
  1650. }
  1651. return null;
  1652. }
  1653.  
  1654. const checkShortsChannelName = (rchannelNameDOM) => {
  1655. let browseId = '';
  1656. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  1657.  
  1658. if (pDom instanceof HTMLElement) {
  1659. const pDomController = insp(pDom);
  1660. const runs = (((pDomController.data || 0).channelTitleText || 0).runs || 0);
  1661. if (runs.length === 1) {
  1662. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  1663. browseId = (browserEndpoint.browseId || '');
  1664. const currentDisplayText = runs[0].text || ''
  1665.  
  1666. if (isUCBrowserId(browseId) && isDisplayAsHandle(currentDisplayText)) {
  1667.  
  1668. if (!channelIdToHandle.has(browseId)) {
  1669. channelIdToHandle.set(browseId, {
  1670. handleText: currentDisplayText.trim(),
  1671. justPossible: true
  1672. });
  1673. }
  1674.  
  1675.  
  1676. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  1677. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  1678. // anchorNode &&
  1679. getDisplayName(browseId).then(fetchResult => {
  1680.  
  1681. if (fetchResult === null) return;
  1682.  
  1683. const { title, langTitle, externalId } = fetchResult;
  1684. const titleForDisplay = langTitle || title;
  1685. if (externalId !== browseId) return; // channel id must be the same
  1686.  
  1687. let hDom = pDom;
  1688. const hDomHostElement = hDom.hostElement || hDom;
  1689. const hDomController = insp(hDom);
  1690. let hData = (hDomController || 0).data || 0;
  1691. const runs = (((hData || 0).channelTitleText || 0).runs || 0);
  1692. if (runs && runs.length === 1 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  1693.  
  1694. let runs2 = [Object.assign({}, runs[0], { text: titleForDisplay })];
  1695.  
  1696.  
  1697. /*
  1698. runs.push({text: title, bold: true, "fontColor": "black",
  1699.  
  1700. size: "SIZE_DEFAULT",
  1701. style: "STYLE_TEXT",
  1702. });
  1703. */
  1704.  
  1705. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: { runs: runs2 }, rSk0e: 1 });
  1706. addCSSRulesIfRequired();
  1707.  
  1708. byPassCheckStore.delete(rchannelNameDOM);
  1709. }
  1710.  
  1711.  
  1712.  
  1713. })
  1714. }
  1715.  
  1716.  
  1717. }
  1718. }
  1719. return browseId
  1720. }
  1721.  
  1722. let firstDOMCheck = false;
  1723. const firstDOMChecker = isMobile ? () => {
  1724.  
  1725. let playerMicroformatRenderer = null;
  1726. try {
  1727. playerMicroformatRenderer = window.ytInitialPlayerResponse.microformat.playerMicroformatRenderer
  1728. } catch (e) { }
  1729. if (playerMicroformatRenderer && playerMicroformatRenderer.ownerChannelName && playerMicroformatRenderer.ownerProfileUrl) {
  1730. cfg.ownerChannelName = playerMicroformatRenderer.ownerChannelName;
  1731. cfg.ownerProfileUrl = playerMicroformatRenderer.ownerProfileUrl.replace(/[\S]+youtube.com\//, 'youtube.com/');
  1732. }
  1733.  
  1734. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  1735. const channelNameCData = !channelNameDOM ? null : insp(channelNameDOM).data;
  1736.  
  1737. if (channelNameCData) {
  1738. let mainChannelUrl = null;
  1739. let mainFormattedNameUrl = null;
  1740. let mainChannelText = null;
  1741. let mainFormattedNameText = null;
  1742. let mainChannelBrowseId = null;
  1743.  
  1744. try {
  1745. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl) // channelUrlUnify("http://www.youtube.com/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  1746. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl) // channelUrlUnify("/channel/UC5CwaMl1eIgY8h02uZw7u8A")
  1747. mainChannelText = channelNameCData.channelName
  1748. mainFormattedNameText = channelNameCData.title.runs[0].text
  1749. mainChannelBrowseId = channelNameCData.navigationEndpoint.browseEndpoint.browseId;
  1750. } catch (e) { }
  1751.  
  1752. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  1753.  
  1754. const channelId = mainChannelBrowseId;
  1755. if (channelId) {
  1756. if (mainChannelText.startsWith('@')) return;
  1757. if (mainChannelText.trim() !== mainChannelText) return;
  1758.  
  1759. displayNameResStore.set(channelId, {
  1760. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1761. externalId: `${channelId}`,
  1762. ownerUrls: [],
  1763. title: mainChannelText,
  1764. vanityChannelUrl: null,
  1765. verified123: true
  1766. });
  1767. }
  1768.  
  1769.  
  1770. }
  1771. }
  1772.  
  1773. } : () => {
  1774.  
  1775. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1776. const channelNameCnt = insp(channelNameDOM);
  1777. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  1778. if (channelNameCData) {
  1779. let mainChannelUrl = null;
  1780. let mainFormattedNameUrl = null;
  1781. let mainChannelText = null;
  1782. let mainFormattedNameText = null;
  1783. let mainChannelBrowseId = null;
  1784. try {
  1785. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1786. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1787. mainChannelText = channelNameCData.channelName.runs[0].text
  1788. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  1789. mainChannelBrowseId = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.browseId;
  1790. } catch (e) { }
  1791.  
  1792. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string' && mainChannelBrowseId && isUCBrowserId(mainChannelBrowseId)) {
  1793.  
  1794. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.exec(mainChannelUrl);
  1795.  
  1796. if (m && m[1] && mainChannelText !== m[1]) {
  1797.  
  1798. const channelHandle = m[1];
  1799. if (/[^-_a-zA-Z0-9.]/.test(mainChannelText)) {
  1800. langPreferredDisplayNameMap.set(channelHandle, mainChannelText);
  1801. }
  1802.  
  1803. } else {
  1804.  
  1805. const channelId = mainChannelBrowseId;
  1806. if (channelId) {
  1807. if (mainChannelText.startsWith('@')) return;
  1808. if (mainChannelText.trim() !== mainChannelText) return;
  1809.  
  1810. displayNameResStore.set(channelId, {
  1811. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1812. externalId: `${channelId}`,
  1813. ownerUrls: [],
  1814. title: mainChannelText,
  1815. vanityChannelUrl: null,
  1816. verified123: true
  1817. });
  1818. }
  1819.  
  1820. }
  1821. }
  1822. }
  1823.  
  1824. };
  1825.  
  1826. // let newAnchorAdded = false;
  1827. /*
  1828.  
  1829. const intersectionobserver = new IntersectionObserver((entries) => {
  1830. let anchorAppear = false;
  1831. for (const entry of entries) {
  1832. if (entry.isIntersecting === true) {
  1833. anchorAppear = true;
  1834. break;
  1835. }
  1836. }
  1837. if (anchorAppear && newAnchorAdded) {
  1838. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1839. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1840. }
  1841. }, {
  1842. rootMargin:"0px 0px 0px 0px",
  1843. threshold:1
  1844. })
  1845. */
  1846.  
  1847.  
  1848. /* globals WeakRef:false */
  1849.  
  1850. /** @type {(o: Object | null) => WeakRef | null} */
  1851. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1852.  
  1853. /** @type {(wr: Object | null) => Object | null} */
  1854. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1855.  
  1856. let doShortsChecking = false;
  1857. let doDescriptionChecking = true;
  1858.  
  1859. let lastNewAnchorLastWR = null;
  1860.  
  1861. const pipelineForDOMMutations = createPipeline();
  1862.  
  1863. const byPassCheckStore = new WeakSet();
  1864.  
  1865. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  1866. for (const mutation of mutations) {
  1867. const target = mutation.target;
  1868. if (!target) continue;
  1869. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  1870. if (!rchannelNameElm) continue;
  1871. const rchannelNameCnt = insp(rchannelNameElm);
  1872. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  1873. const channelId = rchannelNameElm.getAttribute('jkrgy');
  1874. if (channelId) {
  1875. if (byPassCheckStore.has(rchannelNameElm)) continue;
  1876. const object = channelIdToHandle.get(channelId);
  1877. if (object && object.handleText && !object.justPossible) {
  1878. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  1879. if (textDom) {
  1880. let t = textDom.textContent.trim()
  1881. if (t === object.handleText || t === '') {
  1882. rchannelNameElm.removeAttribute('jkrgy');
  1883. Promise.resolve().then(domChecker);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. }
  1889. })
  1890.  
  1891. let domCheckScheduledForShorts = false;
  1892. const domCheckSelectorForShorts = [
  1893. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  1894. ].join(', ');
  1895.  
  1896.  
  1897. const domCheckerForShorts = async () => {
  1898.  
  1899. if (domCheckScheduledForShorts) return;
  1900. if (document.querySelector(domCheckSelectorForShorts) === null) {
  1901. return;
  1902. }
  1903. domCheckScheduledForShorts = true;
  1904.  
  1905. await pipelineForDOMMutations(async () => {
  1906.  
  1907. domCheckScheduledForShorts = false;
  1908. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  1909.  
  1910. try {
  1911.  
  1912. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  1913. if (nodes.length === 0) {
  1914. return;
  1915. }
  1916.  
  1917. for (const node of nodes) {
  1918.  
  1919. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  1920. if (rchannelNameElm) {
  1921. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  1922. childList: true,
  1923. subtree: true
  1924. });
  1925. byPassCheckStore.add(rchannelNameElm);
  1926. const channelId = checkShortsChannelName(rchannelNameElm);
  1927. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  1928. }
  1929.  
  1930. }
  1931.  
  1932. } catch (e) {
  1933. console.log('error occur', e);
  1934. }
  1935.  
  1936. });
  1937. domCheckScheduledForShorts = false;
  1938.  
  1939. };
  1940.  
  1941. const domCheckerForDescriptionAnchor = (s) => {
  1942.  
  1943. findTextNodes(s, (textNode) => {
  1944. const p = textNode.nodeValue;
  1945. const index = p.indexOf('@');
  1946. if (index < 0) return;
  1947. const q = p.substring(index);
  1948. const b = isDisplayAsHandle(q);
  1949. if (b) {
  1950. const href = s.getAttribute('href')
  1951.  
  1952. const channelId = obtainChannelId(href);
  1953. if (channelId) {
  1954. let h = q.trim();
  1955.  
  1956. if (!channelIdToHandle.has(channelId)) {
  1957. channelIdToHandle.set(channelId, {
  1958. handleText: h,
  1959. justPossible: true
  1960. });
  1961. }
  1962.  
  1963. s.setAttribute('jkrgy', channelId);
  1964.  
  1965. getDisplayName(channelId).then(fetchResult => {
  1966.  
  1967. if (fetchResult === null) return;
  1968.  
  1969. const { title, langTitle, externalId } = fetchResult;
  1970. const titleForDisplay = langTitle || title;
  1971. if (externalId !== channelId) return; // channel id must be the same
  1972.  
  1973. const anchorElement = s;
  1974. const anchorTextNode = textNode;
  1975.  
  1976. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  1977.  
  1978. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, titleForDisplay)}`;
  1979.  
  1980. }
  1981.  
  1982. });
  1983. }
  1984. }
  1985. return true;
  1986. });
  1987.  
  1988. }
  1989.  
  1990. // domCheckerForDescription: To be reviwed
  1991. const domCheckerForDescription = isMobile ? () => {
  1992. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  1993. for (const s of document.querySelectorAll('span.yt-core-attributed-string a.yt-core-attributed-string__link.yt-core-attributed-string__link--display-type.yt-core-attributed-string__link--call-to-action-color[href*="channel/"]:not([dxcPj])')) {
  1994. s.setAttribute('dxcPj', '');
  1995. domCheckerForDescriptionAnchor(s);
  1996. }
  1997. } : () => {
  1998. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  1999. for (const s of document.querySelectorAll('yt-attributed-string a.yt-core-attributed-string__link.yt-core-attributed-string__link--display-type.yt-core-attributed-string__link--call-to-action-color[href*="channel/"]:not([dxcPj])')) {
  2000. s.setAttribute('dxcPj', '');
  2001. domCheckerForDescriptionAnchor(s);
  2002. }
  2003. };
  2004.  
  2005. let domCheckScheduled01 = false;
  2006. let domCheckScheduled02 = false;
  2007. const domCheckSelector01 = isMobile ? 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])' : 'a[id][href*="channel/"]:not([jkrgy])'; // old
  2008. const domCheckSelector02 = isMobile ? 'a.comment-icon-container[href*="/@"]:not([jkrgy])' : 'a[id].yt-simple-endpoint.style-scope[href^="/@"]:not([jkrgy])'; // Feb 2024
  2009.  
  2010. const domAuthorNameCheck01 = async () => {
  2011. // Before Feb 2024
  2012.  
  2013. if (domCheckScheduled01) return;
  2014. if (document.querySelector(domCheckSelector01) === null) {
  2015. return;
  2016. }
  2017. domCheckScheduled01 = true;
  2018.  
  2019. await pipelineForDOMMutations(async () => {
  2020.  
  2021. domCheckScheduled01 = false;
  2022. try {
  2023.  
  2024. const newAnchors = document.querySelectorAll(domCheckSelector01);
  2025. if (newAnchors.length === 0) {
  2026. return;
  2027. }
  2028.  
  2029. const cNewAnchorFirst = newAnchors[0]; // non-null
  2030. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  2031. /** @type {HTMLElement | null} */
  2032. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  2033. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  2034.  
  2035. if (!firstDOMCheck) {
  2036. firstDOMCheck = true;
  2037. USE_CHANNEL_META && firstDOMChecker();
  2038. }
  2039.  
  2040. await Promise.resolve();
  2041.  
  2042. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  2043. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  2044. mutex.nextIndex = 0;
  2045. }
  2046. }
  2047.  
  2048. await Promise.resolve();
  2049.  
  2050. // newAnchorAdded = true;
  2051. for (const anchor of newAnchors) {
  2052. // author-text or name
  2053. // normal url: /channel/xxxxxxx
  2054. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  2055. const href = anchor.getAttribute('href');
  2056. const channelId = obtainChannelId(href); // string, can be empty
  2057. if (channelId) {
  2058. anchor.setAttribute('jkrgy', channelId);
  2059. // intersectionobserver.unobserve(anchor);
  2060. // intersectionobserver.observe(anchor); // force first occurance
  2061. domCheckAsync(anchor, href, channelId);
  2062. } else {
  2063. anchor.setAttribute('jkrgy', '');
  2064. }
  2065. }
  2066.  
  2067. } catch (e) {
  2068. console.log('error occur', e);
  2069. }
  2070.  
  2071. });
  2072. domCheckScheduled01 = false;
  2073.  
  2074. };
  2075.  
  2076. const closestYtParent = (dom) => {
  2077. while (dom instanceof Element) {
  2078. if (typeof dom.is === 'string' && dom.is) return dom;
  2079. dom = dom.parentNode;
  2080. }
  2081. return null;
  2082. };
  2083. const closestYtmData = (dom) => {
  2084. while (dom instanceof Element) {
  2085. if (typeof (dom.data || 0) === 'object') return dom;
  2086. dom = dom.parentNode;
  2087. }
  2088. return null;
  2089. };
  2090. const getAuthorBrowseEndpoint = (cnt) => {
  2091. if (isMobile) {
  2092. return (((cnt || 0).data || 0).authorEndpoint || 0).browseEndpoint || null;
  2093. } else {
  2094. return (((cnt || 0).__data || 0).authorTextCommand || 0).browseEndpoint || null;
  2095. }
  2096. };
  2097. const domAuthorNameCheck02 = async () => {
  2098. // Feb 2024
  2099.  
  2100. if (domCheckScheduled02) return;
  2101. if (document.querySelector(domCheckSelector02) === null) {
  2102. return;
  2103. }
  2104. domCheckScheduled02 = true;
  2105.  
  2106. await pipelineForDOMMutations(async () => {
  2107.  
  2108. domCheckScheduled02 = false;
  2109. try {
  2110.  
  2111. const newAnchors = document.querySelectorAll(domCheckSelector02);
  2112. if (newAnchors.length === 0) {
  2113. return;
  2114. }
  2115.  
  2116. const cNewAnchorFirst = newAnchors[0]; // non-null
  2117. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  2118. /** @type {HTMLElement | null} */
  2119. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  2120. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  2121.  
  2122. if (!firstDOMCheck) {
  2123. firstDOMCheck = true;
  2124. USE_CHANNEL_META && firstDOMChecker();
  2125. }
  2126.  
  2127. await Promise.resolve();
  2128.  
  2129. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  2130. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  2131. mutex.nextIndex = 0;
  2132. }
  2133. }
  2134.  
  2135. await Promise.resolve();
  2136.  
  2137. // newAnchorAdded = true;
  2138. for (const anchor of newAnchors) {
  2139. const href = anchor.getAttribute('href');
  2140. let channelId = '';
  2141. const ytElm = isMobile ? closestYtmData(anchor) : closestYtParent(anchor);
  2142. if (ytElm) {
  2143. const cnt = insp(ytElm);
  2144. const { browseId, canonicalBaseUrl } = getAuthorBrowseEndpoint(cnt) || 0;
  2145. if (browseId && canonicalBaseUrl === href && /^\/@[-_a-zA-Z0-9.]{3,30}$/.test(href) && /^UC[-_a-zA-Z0-9+=.]{22}$/.test(browseId)) {
  2146. const handle = href.substring(2);
  2147. channelIdToHandle.set(browseId, {
  2148. handleText: `@${handle}`
  2149. });
  2150. channelId = browseId;
  2151. }
  2152. }
  2153. anchor.setAttribute('jkrgy', channelId);
  2154. if (channelId) {
  2155. domCheckAsync(anchor, href, channelId);
  2156. }
  2157. }
  2158.  
  2159. } catch (e) {
  2160. console.log('error occur', e);
  2161. }
  2162.  
  2163. });
  2164. domCheckScheduled02 = false;
  2165.  
  2166. };
  2167.  
  2168. const domChecker = () => {
  2169.  
  2170. doShortsChecking && domCheckerForShorts();
  2171. doDescriptionChecking && domCheckerForDescription();
  2172. domAuthorNameCheck01();
  2173. domAuthorNameCheck02();
  2174.  
  2175. };
  2176.  
  2177.  
  2178. /** @type {MutationObserver | null} */
  2179. let domObserver = null;
  2180.  
  2181. /** @type {(callback: (event: Event)=>{})} */
  2182. const onPageFetched = isMobile ? (callback) => {
  2183.  
  2184. let state = 0;
  2185.  
  2186. window.addEventListener('state-change', function (evt) {
  2187. if (state === 1) return; // ignore intermediate events
  2188. state = 1; // before value: 0 or 2;
  2189. callback(evt);
  2190. }, false);
  2191.  
  2192. window.addEventListener('state-navigateend', function (evt) { // fallback
  2193. let inSeq = state === 1;
  2194. state = 2; // 2 when loaded
  2195. if (!inSeq) callback(evt);
  2196. }, false);
  2197.  
  2198. } : (callback) => {
  2199.  
  2200. let state = 0;
  2201.  
  2202. document.addEventListener('yt-page-data-fetched', function (evt) {
  2203. if (state === 1) return; // ignore intermediate events if any
  2204. state = 1; // before value: 0 or 2;
  2205. callback(evt);
  2206. }, false);
  2207.  
  2208. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  2209. let inSeq = state === 1;
  2210. state = 2; // 2 when loaded
  2211. if (!inSeq) callback(evt);
  2212. }, false);
  2213.  
  2214. };
  2215.  
  2216. /**
  2217. *
  2218. * @param {Node} app
  2219. * @returns
  2220. */
  2221. function setupOnPageFetched(app) {
  2222.  
  2223. firstDOMCheck = false;
  2224.  
  2225. if (!cfg['INNERTUBE_API_KEY']) {
  2226. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  2227. return;
  2228. }
  2229.  
  2230. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  2231. doShortsChecking = true;
  2232. } else {
  2233. doShortsChecking = false;
  2234. }
  2235.  
  2236. if (!domObserver) {
  2237. domObserver = new MutationObserver(domChecker);
  2238. } else {
  2239. domObserver.takeRecords();
  2240. domObserver.disconnect();
  2241. }
  2242.  
  2243. domObserver.observe(app, { childList: true, subtree: true });
  2244. domChecker();
  2245.  
  2246. }
  2247.  
  2248. /**
  2249. *
  2250. * @param {Object|null} dest
  2251. * @param {Object} ytcfg
  2252. * @param {string[]} keys
  2253. * @returns
  2254. */
  2255. function getYtConfig(dest, ytcfg, keys) {
  2256. dest = dest || {};
  2257. if (typeof ytcfg.get === 'function') { // mobile
  2258. for (const key of keys) {
  2259. dest[key] = ytcfg.get(key);
  2260. }
  2261. } else {
  2262. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  2263. for (const key of keys) {
  2264. dest[key] = cfgData[key];
  2265. }
  2266. }
  2267. return dest;
  2268. }
  2269.  
  2270. /** @type { (evt: Object) => Element | null } */
  2271. const getPageApp = isMobile
  2272. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  2273. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  2274.  
  2275. onPageFetched(async (evt) => {
  2276. const app = getPageApp(evt);
  2277. console.assert(app);
  2278. const ytcfg = ((window || 0).ytcfg || 0);
  2279. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION', 'HL', 'GL']);
  2280. setupOnPageFetched(app);
  2281. });
  2282.  
  2283. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });