Restore YouTube Username from Handle to Custom

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

当前为 2023-07-22 提交的版本,查看 最新版本

  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.8.2
  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. /**
  138. @typedef DisplayNameResultObject
  139. @type {Object}
  140. @property {string} title
  141. @property {string?} externalId
  142. @property {string[]} ownerUrls
  143. @property {string} channelUrl
  144. @property {string} vanityChannelUrl
  145. @property {boolean|undefined} verified123
  146.  
  147. */
  148.  
  149. /**
  150. @typedef ChannelIdToHandleResult
  151. @type {Object}
  152. @property {string} handleText
  153. @property {boolean} justPossible
  154. */
  155.  
  156. (function (__CONTEXT__) {
  157. 'use strict';
  158.  
  159. const USE_RSS_FETCHER = true;
  160. const USE_TIMEOUT_SIGNAL = false;
  161. const USE_CHANNEL_META = true;
  162. const CHANGE_FOR_SHORTS_CHANNEL_NAME = false;
  163.  
  164. /** @type {globalThis.PromiseConstructor} */
  165. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  166.  
  167. const { fetch, JSON, Request, AbortController, setTimeout, clearTimeout } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  168.  
  169. const timeoutSignal = AbortController && USE_TIMEOUT_SIGNAL ? (timeout) => {
  170. let controller = new AbortController();
  171. const r = controller.signal;
  172. let cid = setTimeout(() => {
  173. if (cid >= 1) {
  174. cid = 0;
  175. controller && controller.abort();
  176. controller = null;
  177. }
  178. }, timeout);
  179. r.clearTimeout = () => {
  180. if (cid >= 1) {
  181. clearTimeout(cid);
  182. cid = 0;
  183. }
  184. }
  185. return r;
  186. } : () => { };
  187.  
  188. const fxOperator = (proto, propertyName) => {
  189. let propertyDescriptorGetter = null;
  190. try {
  191. propertyDescriptorGetter = Object.getOwnPropertyDescriptor(proto, propertyName).get;
  192. // https://github.com/cyfung1031/userscript-supports/issues/9
  193. // .parentNode becomes DocumentFragment
  194. /**
  195. *
  196. * Issue Description: YtCustomElements - Custom DOM Operations overrided in FireFox
  197. *
  198. * e.g. ytd-comment-renderer#comment > div#body
  199. *
  200. * ${div#body}.parentNode = DocumentFragment <Node.parentNode>
  201. * ${ytd-comment-renderer#comment}.firstElementChild <Element.firstElementChild>
  202. *
  203. * Cofirmed Affected: parentNode, firstChild, firstElementChild, lastChild, lastElementChild, querySelector, & querySelectorAll
  204. *
  205. * Alternative way: ytCustomElement.$.xxxxxxx
  206. *
  207. */
  208. } catch (e) { }
  209. return typeof propertyDescriptorGetter === 'function' ? (e) => propertyDescriptorGetter.call(e) : (e) => e[propertyName];
  210. };
  211.  
  212. const fxAPI = (proto, propertyName) => {
  213. const methodFunc = proto[propertyName];
  214. return typeof methodFunc === 'function' ? (e, ...args) => methodFunc.apply(e, args) : (e, ...args) => e[propertyName](...args);
  215. };
  216.  
  217. /** @type { (node: Node)=>Node | null } */
  218. const nodeParent = fxOperator(Node.prototype, 'parentNode');
  219. /** @type { (node: Node)=>Node | null } */
  220. const nodeFirstChild = fxOperator(Node.prototype, 'firstChild');
  221. /** @type { (node: Node)=>Node | null } */
  222. const nodeNextSibling = fxOperator(Node.prototype, 'nextSibling');
  223.  
  224. /** @type { (node: ParentNode, selector: string)=>Element | null } */
  225. const elementQS = fxAPI(Element.prototype, 'querySelector');
  226. /** @type { (node: ParentNode, selector: string)=>Element[] } */
  227. const elementQSA = fxAPI(Element.prototype, 'querySelectorAll');
  228.  
  229. /*
  230. init
  231. initialdata
  232. state-progress
  233. state-responsereceived
  234. player-autonav-pause
  235. state-change
  236. state-navigateend
  237. player-initialized
  238. renderer-module-load-start
  239. video-data-change
  240. player-state-change
  241. updateui
  242. renderer-module-load-end -> channel owner DOM available
  243. player-autonav-pause
  244. updateui
  245. renderer-module-load-start
  246. updateui
  247. renderer-module-load-end
  248. playing
  249. h5player.video-progress
  250. h5player.video-progress
  251. h5player.video-progress
  252. h5player.video-progress
  253. ...
  254. navigate new video
  255. state-navigatestart
  256. state-change => channel owener DOM vanished
  257. state-progress
  258. ...
  259. h5player.player-state-change
  260. h5player.video-data-change
  261. h5player.player-state-change
  262. h5player.muted-autoplay-change
  263. h5player.volume-change
  264. h5player.video-data-change
  265. h5player.volume-change
  266. ...
  267. state-progress
  268. ...
  269. state-progress => channel owner DOM appear [just before state-responsereceived]
  270. state-responsereceived
  271. video-data-change
  272. state-change
  273. state-navigateend
  274. UX interaction
  275. user-activity
  276. player-autonav-pause
  277. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  278. EventTarget.prototype.dispatchEvent = function (ev) {
  279. if (ev instanceof Event) {
  280. if (ev.type === 'video-progress') { } else {
  281. console.log(ev.type, this, ev.target)
  282. if (ev.target === null) {
  283. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  284. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  285. }
  286. }
  287. }
  288. return this.uhfsE.apply(this, arguments);
  289. }
  290. */
  291.  
  292. const isMobile = location.hostname === 'm.youtube.com';
  293.  
  294. const cfg = {};
  295. class Mutex {
  296.  
  297. constructor() {
  298. this.p = Promise.resolve()
  299. }
  300.  
  301. /**
  302. * @param {(lockResolve: () => void)} f
  303. */
  304. lockWith(f) {
  305. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  306. }
  307.  
  308. }
  309.  
  310. class OrderedMutex extends Mutex {
  311. constructor() {
  312. super();
  313. this.nextIndex = 0;
  314. this.arr = [];
  315. this.lockFunc = resolve => {
  316. if (this.arr.length >= 1) {
  317. let f = this.arr[0];
  318. if (typeof f === 'function') {
  319. this.arr.shift();
  320. if (this.nextIndex > 0) this.nextIndex--;
  321. f(resolve);
  322. return;
  323. } else {
  324. // reset if unknown error
  325. this.arr.length = 0;
  326. this.nextIndex = 0;
  327. }
  328. }
  329. resolve();
  330. };
  331. }
  332. /**
  333. * @param {(lockResolve: () => void)} f
  334. */
  335. add(f) {
  336. if (this.nextIndex === this.arr.length) {
  337. this.arr.push(f); this.nextIndex++;
  338. } else {
  339. this.arr.splice(this.nextIndex++, 0, f);
  340. }
  341. this.lockWith(this.lockFunc);
  342. }
  343. }
  344. // usage: run network request one by one
  345. const mutex = new OrderedMutex();
  346.  
  347. /**
  348. * @typedef { AsyncValue<T> | T} AsyncOrResolvedValue<T>
  349. * @template T
  350. */
  351.  
  352. //
  353. /**
  354. * usage: cache the network result per web application instance.
  355. * @type {Map<string, AsyncOrResolvedValue<DisplayNameResultObject>>} */
  356. const displayNameResStore = new Map();
  357.  
  358. /**
  359. * usage: mapping the .dataChanged() to the wrapped function - only few entries as most are {ytd-comment-renderer}.dataChanged().
  360. * @type {WeakMap<Function, Function>} */
  361. const dataChangedFuncStore = new WeakMap();
  362.  
  363. /**
  364. * usage: for \@Mention inside comments in YouTube Mobile that without hyperlinks for channelId.
  365. * @type {Map<string, AsyncOrResolvedValue<string>>} */
  366. const handleToChannelId = new Map();
  367.  
  368. /**
  369. * usage: in RSS fetching, no handle text will be obtained from the response. inject the handle into the response.
  370. * @type {Map<string, ChannelIdToHandleResult>} */
  371. const channelIdToHandle = new Map();
  372.  
  373.  
  374. /**
  375. * AsyncValue
  376. * @class
  377. * @template T
  378. */
  379. class AsyncValue {
  380. constructor() {
  381. /** @type {T | null} */
  382. this.__value__ = null;
  383. /** @type {((value: any)=>void) | null} */
  384. this.__resolve__ = null;
  385. this.__promise__ = new Promise(resolve => {
  386. this.__resolve__ = resolve;
  387. });
  388. }
  389. /**
  390. *
  391. * @param {T} value
  392. */
  393. setValue(value) {
  394. const promise = this.__promise__;
  395. if (promise === null) throw 'Value has already been set.';
  396. this.__value__ = value;
  397. this.__promise__ = null;
  398. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  399. }
  400. /**
  401. *
  402. * @returns {Promise<T>}
  403. */
  404. async getValue() {
  405. const promise = this.__promise__;
  406. if (promise === null) return this.__value__;
  407. await promise; // promise become null
  408. this.__promise__ = null; // just in case
  409. this.__resolve__ = null;
  410. return this.__value__;
  411. }
  412. }
  413.  
  414. /**
  415. *
  416. * @param {DisplayNameResultObject} resultInfo
  417. * @param {string} channelId
  418. */
  419. const cacheHandleToChannel = (resultInfo, channelId) => {
  420.  
  421. const { vanityChannelUrl, ownerUrls } = resultInfo;
  422.  
  423. let handleText = urlToHandle(vanityChannelUrl || '');
  424.  
  425. if (handleText) {
  426. // match = true;
  427. } else if ((ownerUrls || 0).length >= 1) {
  428. for (const ownerUrl of ownerUrls) {
  429. handleText = urlToHandle(ownerUrl || '');
  430.  
  431. if (handleText) {
  432. // match = true;
  433. break;
  434. }
  435. }
  436. }
  437. if (handleText) {
  438.  
  439. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  440. if (asyncValue instanceof AsyncValue) {
  441. asyncValue.setValue(channelId);
  442. }
  443. handleToChannelId.set(handleText, channelId);
  444. }
  445.  
  446.  
  447. }
  448.  
  449. /**
  450. *
  451. * @param {string} channelId
  452. * @param {Function} onDownloaded
  453. * @param {Function} onResulted
  454. * @param {Function} onError
  455. */
  456. const fetcherBrowseAPI = (channelId, onDownloaded, onResulted, onError) => {
  457.  
  458. let signal = timeoutSignal(4000);
  459.  
  460. fetch(new Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  461. "method": "POST",
  462. "mode": "same-origin",
  463. "credentials": "omit",
  464.  
  465. referrerPolicy: "no-referrer",
  466. cache: "default", // no effect on POST request
  467. // cache: "force-cache",
  468. redirect: "error", // there shall be no redirection in this API request
  469. integrity: "",
  470. keepalive: false,
  471. signal,
  472.  
  473. "headers": {
  474. "Content-Type": "application/json", // content type of the body data in POST request
  475. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - br
  476. // X-Youtube-Bootstrap-Logged-In: false,
  477. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  478. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  479.  
  480. "Accept": "application/json",
  481. },
  482. "body": JSON.stringify({
  483. "context": {
  484. "client": {
  485. "visitorData": "Cgs0aVg0VjFWM0U0USi0jvOkBg%3D%3D", // [optional] fake visitorData to avoid dynamic visitorData generated in response
  486. "clientName": "MWEB", // "WEB", "MWEB"
  487. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`, // same as WEB version
  488. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  489. "playerType": "UNIPLAYER",
  490. "platform": "MOBILE", // "DESKTOP", "MOBILE", "TABLET"
  491. "clientFormFactor": "SMALL_FORM_FACTOR", // "LARGE_FORM_FACTOR", "SMALL_FORM_FACTOR"
  492. "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",
  493. "mainAppWebInfo": {
  494. "graftUrl": `/channel/${channelId}`,
  495. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  496. "isWebNativeShareAvailable": true
  497. }
  498. },
  499. "user": {
  500. "lockedSafetyMode": false
  501. },
  502. "request": {
  503. "useSsl": true,
  504. "internalExperimentFlags": [],
  505. "consistencyTokenJars": []
  506. }
  507. },
  508. "browseId": `${channelId}`
  509. })
  510. })).then(res => {
  511. signal && signal.clearTimeout && signal.clearTimeout();
  512. signal = null;
  513. onDownloaded();
  514. onDownloaded = null;
  515. return res.json();
  516. }).then(resJson => {
  517. let resultInfo = ((resJson || 0).metadata || 0).channelMetadataRenderer;
  518. onResulted(resultInfo);
  519. onResulted = null;
  520. }).catch(onError);
  521.  
  522. };
  523.  
  524. /**
  525. *
  526. * @param {string} channelId
  527. * @param {Function} onDownloaded
  528. * @param {Function} onResulted
  529. * @param {Function} onError
  530. */
  531. const fetcherRSS = location.origin !== 'https://www.youtube.com' ? null : (channelId, onDownloaded, onResulted, onError) => {
  532.  
  533. let signal = timeoutSignal(4000);
  534. fetch(`https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`, {
  535. // YouTube RSS Response - public, max-age=900
  536.  
  537. "method": "GET",
  538. "mode": "same-origin",
  539. "credentials": "omit",
  540.  
  541. referrerPolicy: "no-referrer",
  542. cache: "default",
  543. // cache: "no-cache",
  544. redirect: "error", // there shall be no redirection in this API request
  545. integrity: "",
  546. keepalive: false,
  547. signal,
  548.  
  549. "headers": {
  550. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  551. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  552. // seems YouTube RSS Feeds server insists its own Cache-Control.
  553.  
  554. // "Content-Type": "text/xml; charset=UTF-8",
  555. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  556. // X-Youtube-Bootstrap-Logged-In: false,
  557. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  558. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  559.  
  560. "Accept": "text/xml",
  561. }
  562. }).then(res => {
  563. signal && signal.clearTimeout && signal.clearTimeout();
  564. signal = null;
  565. onDownloaded();
  566. onDownloaded = null;
  567. return res.text();
  568. }).then(resText => {
  569. let eIdx = resText.indexOf('<entry>');
  570. let mText = (eIdx > 0) ? `${resText.substring(0, eIdx).trim()}</feed>` : resText;
  571.  
  572. // simple: https://www.youtube.com/feeds/videos.xml?channel_id=UC-MUu72gixoYlhV5_mWa36g
  573. // standard: https://www.youtube.com/feeds/videos.xml?channel_id=UCGSfK5HeiIhuFfXoKE47TzA
  574. // long: https://www.youtube.com/feeds/videos.xml?channel_id=UC8cSGjKxDuh2mWG1hDOTdBg
  575. // special: http://www.youtube.com/feeds/videos.xml?channel_id=UCmZ2-GUxmdWFKfXA5IN0x-w
  576.  
  577.  
  578. let name, uri, mt;
  579.  
  580. // ===============================================================
  581.  
  582. /* removed in 2023.06.30 */
  583.  
  584.  
  585. // ===============================================================
  586.  
  587.  
  588. const wIdx1 = mText.indexOf('<author>');
  589. const wIdx2 = wIdx1 > 0 ? mText.indexOf('</author>', wIdx1 + 8) : -1;
  590.  
  591. if (wIdx1 > 0 && wIdx2 > 0) {
  592. let qText = mText.substring(wIdx1, wIdx2 + '</author>'.length);
  593. const template = document.createElement('template');
  594. template.innerHTML = qText;
  595. /** @type {HTMLElement | null} */
  596. let authorChild = ((template.content || 0).firstElementChild || 0).firstElementChild;
  597. for (; authorChild !== null; authorChild = authorChild.nextElementSibling) {
  598. const nodeName = authorChild.nodeName;
  599. if (nodeName === 'NAME') name = authorChild.textContent;
  600. else if (nodeName === 'URI') {
  601. uri = authorChild.textContent;
  602. mt = obtainChannelId(uri);
  603. }
  604. }
  605. template.innerHTML = '';
  606. }
  607.  
  608. if (!name && !uri) {
  609.  
  610. // fallback
  611.  
  612. const parser = new DOMParser();
  613. const xmlDoc = parser.parseFromString(mText, "text/xml");
  614.  
  615. // const author = xmlDoc.querySelector("author");
  616.  
  617. // https://extendsclass.com/xpath-tester.html
  618.  
  619. const authorChilds = xmlDoc.evaluate("//*[name()='author']/*", xmlDoc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
  620.  
  621. let authorChild;
  622. while ((authorChild = authorChilds.iterateNext()) !== null) {
  623. if (authorChild.nodeName === 'name') name = authorChild.textContent;
  624. else if (authorChild.nodeName === 'uri') {
  625. uri = authorChild.textContent;
  626. mt = obtainChannelId(uri)
  627. }
  628. }
  629.  
  630. try {
  631. xmlDoc.firstChild.remove();
  632. } catch (e) { }
  633.  
  634. }
  635.  
  636.  
  637.  
  638.  
  639. let res = null;
  640.  
  641. if (name && uri && mt && mt === channelId) {
  642.  
  643.  
  644. let object = channelIdToHandle.get(mt);
  645.  
  646. if (object) {
  647.  
  648. if (object.handleText === name) channelIdToHandle.delete(mt);
  649. else {
  650. object.justPossible = false; // ignore @handle checking
  651.  
  652. res = {
  653. "title": name,
  654. "externalId": mt,
  655. "ownerUrls": [
  656. `http://www.youtube.com/${object.handleText}`
  657. ],
  658. "channelUrl": uri,
  659. "vanityChannelUrl": `http://www.youtube.com/${object.handleText}`
  660. };
  661.  
  662. }
  663. }
  664. }
  665.  
  666. onResulted(res);
  667. onResulted = null;
  668.  
  669. // let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  670. // onResulted(resultInfo);
  671. }).catch(onError);
  672.  
  673.  
  674.  
  675. }
  676.  
  677. /**
  678. *
  679. * @param {string} channelId
  680. */
  681. function stackNewRequest(channelId) {
  682.  
  683. mutex.add(lockResolve => {
  684.  
  685. let bResult = displayNameResStore.get(channelId);
  686. if (!(bResult instanceof AsyncValue)) {
  687. // resolved or removed
  688. lockResolve(); lockResolve = null;
  689. return;
  690. }
  691.  
  692. let setResult = (result) => {
  693. setResult = null;
  694. if (!result) {
  695. bResult.fetchingState = 0;
  696. bResult.setValue(null);
  697. displayNameResStore.delete(channelId); // create another network response in the next request
  698. } else {
  699. bResult.fetchingState = 4;
  700. bResult.setValue(result);
  701. displayNameResStore.set(channelId, result); // update store result to resolved value
  702. }
  703. bResult = null;
  704. }
  705.  
  706. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  707. // request is already done. no need to stack any request
  708. lockResolve(); lockResolve = null;
  709. return;
  710. }
  711.  
  712. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  713. // element has already been removed
  714. lockResolve(); lockResolve = null;
  715. setResult(null);
  716. return;
  717. }
  718.  
  719. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  720.  
  721. bResult.fetchingState = 2;
  722.  
  723.  
  724. // note: when setResult(null), the fetch will be requested again if the same username appears. (multiple occurrences)
  725. // consider the network problem might be fixed in the 2nd attempt, the name will be changed in the 2nd attempt but ignore 1st attempt.
  726. const fetcher = USE_RSS_FETCHER && fetcherRSS && channelIdToHandle.has(channelId) ? fetcherRSS : fetcherBrowseAPI;
  727. fetcher(channelId, () => {
  728. bResult.fetchingState = 3;
  729. lockResolve();
  730. lockResolve = null;
  731. }, resultInfo => {
  732.  
  733. if (!resultInfo) {
  734. // invalid json format
  735. setResult(null);
  736. return;
  737. }
  738.  
  739. cacheHandleToChannel(resultInfo, channelId);
  740.  
  741. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  742.  
  743. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  744.  
  745. setResult(displayNameRes);
  746. }, e => {
  747. lockResolve && lockResolve();
  748. lockResolve = null;
  749. console.warn(e);
  750. setResult && setResult(null);
  751. });
  752.  
  753. });
  754.  
  755. }
  756.  
  757. /**
  758. *
  759. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  760. * @returns Example: _\@yr__kd_
  761. */
  762. function urlToHandle(url) {
  763.  
  764. if (typeof url !== 'string') return '';
  765. let i = url.indexOf('.youtube.com/');
  766. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  767. else if (url.charAt(0) === '/') url = url.substring(1);
  768. return isDisplayAsHandle(url) ? url : '';
  769.  
  770. }
  771.  
  772. /**
  773. *
  774. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  775. * @returns {Promise<DisplayNameResultObject | null>}
  776. */
  777. async function getDisplayName(channelId) {
  778.  
  779. let cache = displayNameResStore.get(channelId);
  780. let isStackNewRequest = false;
  781.  
  782. /** @type {AsyncValue<DisplayNameResultObject> | null | undefined} */
  783. let aResult;
  784.  
  785. if (cache instanceof AsyncValue) {
  786. aResult = cache;
  787. if (aResult.fetchingState >= 2) {
  788. // aResult.fetchingState
  789. // 2: network fetch started
  790. // 3: network fetch ended
  791. // isStackNewRequest = false;
  792. } else {
  793. // 0: invalid before
  794. // 1: scheduled but not yet fetch
  795. isStackNewRequest = true;
  796. }
  797. } else if (cache) {
  798. // resolved result
  799. return cache;
  800. } else {
  801. // else no cached value found
  802. /** @type {AsyncValue<DisplayNameResultObject>} */
  803. aResult = new AsyncValue();
  804. displayNameResStore.set(channelId, aResult);
  805. isStackNewRequest = true;
  806. }
  807.  
  808. if (isStackNewRequest) {
  809. aResult.fetchingState = 1;
  810. stackNewRequest(channelId);
  811. }
  812. return await aResult.getValue();
  813. }
  814.  
  815.  
  816. /**
  817. *
  818. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  819. * @returns
  820. */
  821. const obtainChannelId = (href) => {
  822. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  823. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  824. return !m ? '' : (m[1] || '');
  825. };
  826.  
  827.  
  828. /**
  829. *
  830. * @param {Element} ytElm
  831. */
  832. const resetWhenDataChanged = (ytElm) => {
  833. if (ytElm instanceof Element) {
  834. const anchors = elementQSA(ytElm, 'a[id][href*="channel/"][jkrgy]');
  835. if ((anchors || 0).length >= 1 && ((ytElm.inst || ytElm).data || 0).jkrgx !== 1) {
  836. for (const anchor of anchors) {
  837. anchor.removeAttribute('jkrgy');
  838. }
  839. }
  840. }
  841. }
  842.  
  843. /**
  844. *
  845. * @param {Function} dataChanged original dataChanged function
  846. * @returns new dataChanged function
  847. */
  848. const dataChangeFuncProducer = (dataChanged) => {
  849. /** @this HTMLElement */
  850. return function () {
  851. resetWhenDataChanged(this);
  852. return dataChanged.apply(this, arguments);
  853. }
  854. };
  855.  
  856. /**
  857. *
  858. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  859. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  860. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  861. * @returns
  862. */
  863. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  864.  
  865. let currentHref = anchor.getAttribute('href');
  866. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  867.  
  868. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  869.  
  870. };
  871.  
  872. /**
  873. *
  874. * @param {string} currentDisplayed
  875. * @param {DisplayNameResultObject} fetchResult
  876. * @returns
  877. */
  878. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  879.  
  880. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  881.  
  882. const currentDisplayTrimmed = currentDisplayed.trim();
  883. let match = false;
  884. if (verified123) {
  885. match = true;
  886. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  887. match = true;
  888. } else if ((ownerUrls || 0).length >= 1) {
  889. for (const ownerUrl of ownerUrls) {
  890. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  891. match = true;
  892. break;
  893. }
  894. }
  895. }
  896. if (match) {
  897. return currentDisplayTrimmed;
  898. }
  899. return '';
  900.  
  901. };
  902.  
  903. /**
  904. *
  905. *
  906. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  907. - Is between 3-30 characters
  908. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  909. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  910. - Is not URL-like or phone number-like
  911. - Is not already being used
  912. - Follows YouTube's Community Guidelines
  913. ### Handle automatically generated by YouTube
  914. - `@user-XXXX`
  915. - without dot (.)
  916. *
  917. * @param {string} text
  918. * @returns
  919. */
  920. const isDisplayAsHandle = (text) => {
  921.  
  922. if (typeof text !== 'string') return false;
  923. if (text.length < 4) return false;
  924. if (text.indexOf('@') < 0) return false;
  925. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  926.  
  927. };
  928.  
  929. /**
  930. *
  931. * @param {Object[]} contentTexts
  932. * @param {number} idx
  933. * @returns
  934. */
  935. const contentTextProcess = (contentTexts, idx) => {
  936. const contentText = contentTexts[idx];
  937. const text = (contentText || 0).text;
  938. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  939. if (typeof url === 'string' && typeof text === 'string') {
  940.  
  941. if (!isDisplayAsHandle(text)) return null;
  942. const channelId = obtainChannelId(url);
  943.  
  944. return getDisplayName(channelId).then(fetchResult => {
  945. let resolveResult = null;
  946. if (fetchResult) {
  947. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  948.  
  949. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  950. if (textTrimmed) {
  951. resolveResult = (md) => {
  952. let runs = ((md || 0).contentText || 0).runs;
  953. if (!runs || !runs[idx]) return;
  954. if (runs[idx].text !== text) return;
  955. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  956. md.contentText = Object.assign({}, md.contentText);
  957. };
  958. }
  959. }
  960. return resolveResult; // function as a Promise
  961. });
  962. }
  963.  
  964. return null;
  965. };
  966.  
  967. /**
  968. *
  969. * @param {ParentNode} parentNode
  970. * @param {Function} callback
  971. */
  972. function findTextNodes(parentNode, callback) {
  973. /**
  974. *
  975. * @param {Node} node
  976. * @returns
  977. */
  978. function traverse(node) {
  979. if (node.nodeType === Node.TEXT_NODE) {
  980. let r = callback(node);
  981. if (r === true) return true;
  982. }
  983.  
  984. let childNode = nodeFirstChild(node);
  985. while (childNode) {
  986. let r = traverse(childNode);
  987. if (r === true) return true;
  988. childNode = nodeNextSibling(childNode);
  989. }
  990. }
  991.  
  992. traverse(parentNode);
  993. }
  994.  
  995. /**
  996. *
  997. * @param {ParentNode} parentNode
  998. * @param {Object[]} contentTexts
  999. * @param {number} aidx
  1000. * @returns
  1001. */
  1002. const mobileContentHandleAsync = async (parentNode, contentTexts, aidx) => {
  1003.  
  1004.  
  1005. let commentText = elementQS(parentNode, '.comment-text');
  1006. if (!commentText) return;
  1007. commentText = elementQS(commentText, '.yt-core-attributed-string') || commentText;
  1008. let currentText = commentText.textContent;
  1009. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  1010. if (!textMatch) return;
  1011.  
  1012. const contentText = contentTexts[aidx];
  1013.  
  1014. /** @type {string} */
  1015. const handleText = contentText.text.trim();
  1016. /** @type {string | null | undefined} */
  1017. let channelId;
  1018.  
  1019. let cache = handleToChannelId.get(handleText);
  1020.  
  1021. if (typeof cache === 'string') {
  1022. channelId = cache;
  1023. } else if (cache instanceof AsyncValue) {
  1024. channelId = await cache.getValue();
  1025. } else {
  1026. /** @type {AsyncValue<string>} */
  1027. const asyncValue = new AsyncValue();
  1028. handleToChannelId.set(handleText, asyncValue);
  1029. channelId = await asyncValue.getValue(); // note: it could be never resolved
  1030. }
  1031.  
  1032. if (!channelId) return; // just in case
  1033.  
  1034. if (commentText.isConnected !== true) return; // already removed
  1035. if (commentText.textContent !== currentText) return; // already changed
  1036.  
  1037. const fetchResult = await getDisplayName(channelId);
  1038.  
  1039. if (fetchResult === null) return;
  1040.  
  1041. const { title, externalId } = fetchResult;
  1042. if (externalId !== channelId) return; // channel id must be the same
  1043.  
  1044. if (commentText.isConnected !== true) return; // already removed
  1045. if (commentText.textContent !== currentText) return; // already changed
  1046.  
  1047. let search = contentText.text;
  1048. if (typeof search === 'string') {
  1049.  
  1050. const searchTrimmed = search.trim();
  1051. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  1052. contentText.text = search.replace(searchTrimmed, "@" + title);
  1053.  
  1054. findTextNodes(commentText, (textnode) => {
  1055. if (textnode.nodeValue.indexOf(search) >= 0) {
  1056. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  1057. return true;
  1058. }
  1059. });
  1060. }
  1061.  
  1062. }
  1063.  
  1064. }
  1065.  
  1066. /**
  1067. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  1068. * @type { (anchor: HTMLElement, channelHref: string?, mt: string?) => Promise<void> }
  1069. */
  1070. const domCheckAsync = isMobile ? async (anchor, channelHref, mt) => {
  1071.  
  1072. try {
  1073. if (!channelHref || !mt) return;
  1074. let parentNode = nodeParent(anchor);
  1075. while (parentNode instanceof Node) {
  1076. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  1077. parentNode = nodeParent(parentNode);
  1078. }
  1079. if (parentNode instanceof Node) { } else return;
  1080.  
  1081. let displayTextDOM = elementQS(parentNode, '.comment-header .comment-title');
  1082. if (!displayTextDOM) return;
  1083. displayTextDOM = elementQS(displayTextDOM, '.yt-core-attributed-string') || displayTextDOM;
  1084. let airaLabel = anchor.getAttribute('aria-label')
  1085. const parentNodeData = (parentNode.inst || parentNode).data;
  1086. let runs = ((parentNodeData || 0).authorText || 0).runs;
  1087.  
  1088. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  1089.  
  1090. if (!channelIdToHandle.has(mt)) {
  1091. channelIdToHandle.set(mt, {
  1092. handleText: airaLabel.trim(),
  1093. justPossible: true
  1094. });
  1095. }
  1096.  
  1097. const fetchResult = await getDisplayName(mt);
  1098.  
  1099. if (fetchResult === null) return;
  1100.  
  1101. const { title, externalId } = fetchResult;
  1102.  
  1103. if (externalId !== mt) return; // channel id must be the same
  1104.  
  1105. // anchor href might be changed by external
  1106. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1107.  
  1108. if (displayTextDOM.isConnected !== true) return; // already removed
  1109.  
  1110. let found = false;
  1111.  
  1112. findTextNodes(displayTextDOM, (textnode) => {
  1113. if (textnode.nodeValue === airaLabel) {
  1114. textnode.nodeValue = title;
  1115. found = true;
  1116. return true;
  1117. }
  1118. });
  1119.  
  1120. if (!found) return;
  1121. anchor.setAttribute('aria-label', title);
  1122. runs[0].text = title;
  1123.  
  1124.  
  1125. const contentTexts = (parentNodeData.contentText || 0).runs;
  1126. if (contentTexts && contentTexts.length >= 2) {
  1127. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1128. const contentText = contentTexts[aidx] || 0;
  1129. if (contentText.italics !== true) {
  1130. let isHandle = isDisplayAsHandle(contentText.text);
  1131. if (isHandle) {
  1132. mobileContentHandleAsync(parentNode, contentTexts, aidx);
  1133. }
  1134. }
  1135. }
  1136. }
  1137.  
  1138. }
  1139. } catch (e) {
  1140. console.warn(e);
  1141. }
  1142.  
  1143. } : async (anchor, channelHref, mt) => {
  1144.  
  1145. try {
  1146. if (!channelHref || !mt) return;
  1147. let parentNode = nodeParent(anchor);
  1148. while (parentNode instanceof Node) {
  1149. const cnt = parentNode.inst || parentNode;
  1150. if (typeof cnt.is === 'string' && typeof cnt.dataChanged === 'function') break;
  1151. parentNode = nodeParent(parentNode);
  1152. }
  1153. if (parentNode instanceof Node) { } else return;
  1154. const parentNodeController = parentNode.inst || parentNode;
  1155. const authorText = (parentNodeController.data || 0).authorText;
  1156. const currentDisplayed = (authorText || 0).simpleText;
  1157. if (typeof currentDisplayed !== 'string') return;
  1158. if (!isDisplayAsHandle(currentDisplayed)) return;
  1159.  
  1160. if (!channelIdToHandle.has(mt)) {
  1161. channelIdToHandle.set(mt, {
  1162. handleText: currentDisplayed.trim(),
  1163. justPossible: true
  1164. });
  1165. }
  1166.  
  1167. const oldDataChanged = parentNodeController.dataChanged;
  1168. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  1169. let newDataChanged = dataChangedFuncStore.get(oldDataChanged);
  1170. if (!newDataChanged) {
  1171. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  1172. newDataChanged.jkrgx = 1;
  1173. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  1174. }
  1175. parentNodeController.dataChanged = newDataChanged;
  1176. }
  1177.  
  1178. const fetchResult = await getDisplayName(mt);
  1179.  
  1180. if (fetchResult === null) return;
  1181.  
  1182. const { title, externalId } = fetchResult;
  1183.  
  1184. if (externalId !== mt) return; // channel id must be the same
  1185.  
  1186. // anchor href might be changed by external
  1187. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  1188.  
  1189. const parentNodeData = parentNodeController.data;
  1190. const funcPromises = [];
  1191.  
  1192. if (parentNodeController.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  1193.  
  1194. if (authorText.simpleText !== currentDisplayed) return;
  1195. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  1196. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  1197. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  1198.  
  1199. // the inside hyperlinks will be only converted if its parent author name is handle
  1200. const contentTexts = (parentNodeData.contentText || 0).runs;
  1201. if (contentTexts && contentTexts.length >= 1) {
  1202. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  1203. const r = contentTextProcess(contentTexts, aidx);
  1204. if (r instanceof Promise) funcPromises.push(r);
  1205. }
  1206. }
  1207.  
  1208. const md = Object.assign({}, parentNodeData);
  1209. let setBadge = false;
  1210. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  1211. setBadge = true;
  1212. }
  1213. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  1214. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  1215. if (setBadge) {
  1216. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  1217. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  1218. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  1219.  
  1220. }
  1221. if (funcPromises.length >= 1) {
  1222. let funcs = await Promise.all(funcPromises);
  1223.  
  1224. for (const func of funcs) {
  1225. if (typeof func === 'function') {
  1226. func(md);
  1227. }
  1228. }
  1229. }
  1230.  
  1231. if (parentNodeController.isAttached === true && parentNode.isConnected === true) {
  1232. parentNodeController.data = Object.assign({}, md, { jkrgx: 1 });
  1233. }
  1234.  
  1235.  
  1236. }
  1237.  
  1238. }
  1239. } catch (e) {
  1240. console.warn(e);
  1241. }
  1242.  
  1243. }
  1244.  
  1245. /**
  1246. *
  1247. * @param {string} url
  1248. * @returns
  1249. */
  1250. const channelUrlUnify = (url) => {
  1251.  
  1252. if (typeof url !== 'string') return url; // type unchanged
  1253. let c0 = url.charAt(0);
  1254. if (c0 === '/') return url;
  1255. let i = url.indexOf('.youtube.com/');
  1256. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  1257. else if (url.charAt(0) !== '/') url = '/' + url;
  1258. return url
  1259.  
  1260. }
  1261.  
  1262. const parentYtElement = (node, nodeName, maxN) => {
  1263. for (let pDom = nodeParent(node); (pDom instanceof HTMLElement) && maxN-- > 0; pDom = nodeParent(pDom)) {
  1264. if (pDom.nodeName === nodeName) {
  1265. return pDom;
  1266. }
  1267. }
  1268. return null;
  1269. }
  1270.  
  1271. const checkShortsChannelName = (rchannelNameDOM) => {
  1272. let browseId = '';
  1273. const pDom = parentYtElement(rchannelNameDOM, 'YTD-REEL-PLAYER-HEADER-RENDERER', 18);
  1274.  
  1275. if (pDom instanceof HTMLElement) {
  1276. const pDomController = pDom.inst || pDom;
  1277. const runs = (((pDomController.data || 0).channelTitleText || 0).runs || 0);
  1278. if (runs.length === 1) {
  1279. const browserEndpoint = (((runs[0] || 0).navigationEndpoint || 0).browseEndpoint || 0);
  1280. browseId = (browserEndpoint.browseId || '');
  1281. const currentDisplayText = runs[0].text || ''
  1282.  
  1283. if (/^UC[-_a-zA-Z0-9+=.]+$/.test(browseId) && isDisplayAsHandle(currentDisplayText)) {
  1284.  
  1285. if (!channelIdToHandle.has(browseId)) {
  1286. channelIdToHandle.set(browseId, {
  1287. handleText: currentDisplayText.trim(),
  1288. justPossible: true
  1289. });
  1290. }
  1291.  
  1292.  
  1293. // let anchorNode = elementQS(rchannelNameDOM, `a[href="${browserEndpoint.canonicalBaseUrl}"]`);
  1294. // anchorNode && anchorNode.setAttribute('jkrgy', browseId); // for checking
  1295. // anchorNode &&
  1296. getDisplayName(browseId).then(fetchResult => {
  1297.  
  1298. if (fetchResult === null) return;
  1299.  
  1300. const { title, externalId } = fetchResult;
  1301. if (externalId !== browseId) return; // channel id must be the same
  1302.  
  1303. let hDom = pDom;
  1304. const hDomHostElement = hDom.hostElement || hDom;
  1305. const hDomController = hDom.inst || hDom;
  1306. let hData = (hDomController || 0).data || 0;
  1307. const runs = (((hData || 0).channelTitleText || 0).runs || 0);
  1308. if (runs && runs.length === 1 && (runs[0] || 0).text === currentDisplayText && hDomHostElement.isConnected === true) {
  1309.  
  1310. let runs2 = [Object.assign({}, runs[0], { text: title })];
  1311.  
  1312.  
  1313. /*
  1314. runs.push({text: title, bold: true, "fontColor": "black",
  1315. size: "SIZE_DEFAULT",
  1316. style: "STYLE_TEXT",
  1317. });
  1318. */
  1319.  
  1320. hDomController.data = Object.assign({}, hDomController.data, { channelTitleText: { runs: runs2 }, rSk0e: 1 });
  1321.  
  1322. byPassCheckStore.delete(rchannelNameDOM);
  1323. }
  1324.  
  1325.  
  1326.  
  1327. })
  1328. }
  1329.  
  1330.  
  1331. }
  1332. }
  1333. return browseId
  1334. }
  1335.  
  1336. let firstDOMCheck = false;
  1337. const firstDOMChecker = isMobile ? () => {
  1338.  
  1339. const channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  1340. const channelNameCData = !channelNameDOM ? null : (channelNameDOM.inst || channelNameDOM || 0).data;
  1341.  
  1342. if (channelNameCData) {
  1343. let mainChannelUrl = null;
  1344. let mainFormattedNameUrl = null;
  1345. let mainChannelText = null;
  1346. let mainFormattedNameText = null;
  1347.  
  1348. try {
  1349. mainChannelUrl = channelUrlUnify(channelNameCData.channelUrl)
  1350. mainFormattedNameUrl = channelUrlUnify(channelNameCData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  1351. mainChannelText = channelNameCData.channelName
  1352. mainFormattedNameText = channelNameCData.title.runs[0].text
  1353. } catch (e) { }
  1354.  
  1355. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1356.  
  1357.  
  1358. let channelId = obtainChannelId(mainChannelUrl);
  1359. if (channelId) {
  1360. if (mainChannelText.startsWith('@')) return;
  1361. if (mainChannelText.trim() !== mainChannelText) return;
  1362.  
  1363. displayNameResStore.set(channelId, {
  1364. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1365. externalId: `${channelId}`,
  1366. ownerUrls: [],
  1367. title: mainChannelText,
  1368. vanityChannelUrl: null,
  1369. verified123: true
  1370. });
  1371. }
  1372.  
  1373.  
  1374. }
  1375. }
  1376.  
  1377. } : () => {
  1378.  
  1379. const channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1380. const channelNameCnt = !channelNameDOM ? null : channelNameDOM.inst || channelNameDOM;
  1381. const channelNameCData = (channelNameCnt || 0).__data || (channelNameDOM || 0).__data;
  1382. if (channelNameCData) {
  1383. let mainChannelUrl = null;
  1384. let mainFormattedNameUrl = null;
  1385. let mainChannelText = null;
  1386. let mainFormattedNameText = null;
  1387.  
  1388. try {
  1389. mainChannelUrl = channelNameCData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1390. mainFormattedNameUrl = channelNameCData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1391. mainChannelText = channelNameCData.channelName.runs[0].text
  1392. mainFormattedNameText = channelNameCData.formattedName.runs[0].text
  1393. } catch (e) { }
  1394.  
  1395. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1396.  
  1397. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.test(mainChannelUrl);
  1398.  
  1399. if (m && m[1] && mainChannelText !== m[1]) {
  1400.  
  1401. let channelId = obtainChannelId(mainChannelUrl);
  1402. if (channelId) {
  1403. if (mainChannelText.startsWith('@')) return;
  1404. if (mainChannelText.trim() !== mainChannelText) return;
  1405.  
  1406. displayNameResStore.set(channelId, {
  1407. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1408. externalId: `${channelId}`,
  1409. ownerUrls: [],
  1410. title: mainChannelText,
  1411. vanityChannelUrl: null,
  1412. verified123: true
  1413. });
  1414. }
  1415.  
  1416. }
  1417. }
  1418. }
  1419.  
  1420. };
  1421.  
  1422. // let newAnchorAdded = false;
  1423. /*
  1424. const intersectionobserver = new IntersectionObserver((entries) => {
  1425. let anchorAppear = false;
  1426. for (const entry of entries) {
  1427. if (entry.isIntersecting === true) {
  1428. anchorAppear = true;
  1429. break;
  1430. }
  1431. }
  1432. if (anchorAppear && newAnchorAdded) {
  1433. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1434. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1435. }
  1436. }, {
  1437. rootMargin:"0px 0px 0px 0px",
  1438. threshold:1
  1439. })
  1440. */
  1441.  
  1442.  
  1443. /* globals WeakRef:false */
  1444.  
  1445. /** @type {(o: Object | null) => WeakRef | null} */
  1446. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1447.  
  1448. /** @type {(wr: Object | null) => Object | null} */
  1449. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1450.  
  1451. let doShortsChecking = false;
  1452. let doDescriptionChecking = true;
  1453.  
  1454. let lastNewAnchorLastWR = null;
  1455.  
  1456. const mutexForDOMMutations = new Mutex();
  1457.  
  1458. const byPassCheckStore = new WeakSet();
  1459.  
  1460. const mutObserverForShortsChannelName = new MutationObserver((mutations) => {
  1461. for (const mutation of mutations) {
  1462. const target = mutation.target;
  1463. if (!target) continue;
  1464. const rchannelNameElm = parentYtElement(target, 'YTD-CHANNEL-NAME', 18);
  1465. if (!rchannelNameElm) continue;
  1466. const rchannelNameCnt = rchannelNameElm.inst || rchannelNameElm;
  1467. if ((rchannelNameCnt.data || 0).rSk0e) continue;
  1468. const channelId = rchannelNameElm.getAttribute('jkrgy');
  1469. if (channelId) {
  1470. if (byPassCheckStore.has(rchannelNameElm)) continue;
  1471. const object = channelIdToHandle.get(channelId);
  1472. if (object && object.handleText && !object.justPossible) {
  1473. const textDom = ((rchannelNameCnt.$ || 0).text || 0);
  1474. if (textDom) {
  1475. let t = textDom.textContent.trim()
  1476. if (t === object.handleText || t === '') {
  1477. rchannelNameElm.removeAttribute('jkrgy');
  1478. Promise.resolve().then(domChecker);
  1479. }
  1480. }
  1481. }
  1482. }
  1483. }
  1484. })
  1485.  
  1486. let domCheckScheduledForShorts = false;
  1487. const domCheckSelectorForShorts = [
  1488. 'ytd-channel-name.ytd-reel-player-header-renderer:not([jkrgy]) a.yt-simple-endpoint[href]'
  1489. ].join(', ');
  1490. const domCheckerForShorts = () => {
  1491.  
  1492. if (domCheckScheduledForShorts) return;
  1493. if (document.querySelector(domCheckSelectorForShorts) === null) {
  1494. return;
  1495. }
  1496. domCheckScheduledForShorts = true;
  1497.  
  1498. mutexForDOMMutations.lockWith(lockResolve => {
  1499.  
  1500.  
  1501. // setTimeout(()=>{ // delay due to data update is after [is-active] switching
  1502.  
  1503.  
  1504. domCheckScheduledForShorts = false;
  1505.  
  1506. const nodes = document.querySelectorAll(domCheckSelectorForShorts);
  1507. if (nodes.length === 0) {
  1508. lockResolve();
  1509. return;
  1510. }
  1511.  
  1512. for (const node of nodes) {
  1513.  
  1514. const rchannelNameElm = parentYtElement(node, 'YTD-CHANNEL-NAME', 18);
  1515. if (rchannelNameElm) {
  1516. mutObserverForShortsChannelName.observe(rchannelNameElm, {
  1517. childList: true,
  1518. subtree: true
  1519. });
  1520. let channelId = '';
  1521. byPassCheckStore.add(rchannelNameElm);
  1522. channelId = checkShortsChannelName(rchannelNameElm);
  1523. rchannelNameElm.setAttribute('jkrgy', channelId || '');
  1524. }
  1525.  
  1526. }
  1527.  
  1528. lockResolve();
  1529.  
  1530. // }, 80);
  1531.  
  1532.  
  1533. })
  1534.  
  1535. }
  1536.  
  1537. const domCheckerForDescriptionAnchor = (s) => {
  1538.  
  1539. findTextNodes(s, (textNode) => {
  1540. const p = textNode.nodeValue;
  1541. const index = p.indexOf('@');
  1542. if (index < 0) return;
  1543. const q = p.substring(index);
  1544. const b = isDisplayAsHandle(q);
  1545. if (b) {
  1546. const href = s.getAttribute('href')
  1547.  
  1548. const channelId = obtainChannelId(href);
  1549. if (channelId) {
  1550. let h = q.trim();
  1551.  
  1552. if (!channelIdToHandle.has(channelId)) {
  1553. channelIdToHandle.set(channelId, {
  1554. handleText: h,
  1555. justPossible: true
  1556. });
  1557. }
  1558.  
  1559. s.setAttribute('jkrgy', channelId);
  1560.  
  1561. getDisplayName(channelId).then(fetchResult => {
  1562.  
  1563. if (fetchResult === null) return;
  1564.  
  1565. const { title, externalId } = fetchResult;
  1566. if (externalId !== channelId) return; // channel id must be the same
  1567.  
  1568. const anchorElement = s;
  1569. const anchorTextNode = textNode;
  1570.  
  1571. if (anchorElement.isConnected === true && anchorTextNode.isConnected === true && anchorElement.contains(anchorTextNode) && anchorTextNode.nodeValue === p && s.getAttribute('href') === href) {
  1572.  
  1573. anchorTextNode.nodeValue = `${p.substring(0, index)}${q.replace(h, title)}`;
  1574.  
  1575. }
  1576.  
  1577. });
  1578. }
  1579. }
  1580. return true;
  1581. });
  1582.  
  1583. }
  1584. const domCheckerForDescription = isMobile ? ()=>{
  1585. // example https://m.youtube.com/watch?v=jKt4Ah47L7Q
  1586. 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])')) {
  1587. s.setAttribute('dxcPj', '');
  1588. domCheckerForDescriptionAnchor(s);
  1589. }
  1590. } : () => {
  1591. // example https://www.youtube.com/watch?v=jKt4Ah47L7Q
  1592. 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])')) {
  1593. s.setAttribute('dxcPj', '');
  1594. domCheckerForDescriptionAnchor(s);
  1595. }
  1596. };
  1597.  
  1598. let domCheckScheduled = false;
  1599. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]:not([jkrgy])' : 'a[id][href*="channel/"]:not([jkrgy])';
  1600. const domChecker = () => {
  1601.  
  1602. doShortsChecking && domCheckerForShorts();
  1603. doDescriptionChecking && domCheckerForDescription();
  1604.  
  1605. if (domCheckScheduled) return;
  1606. if (document.querySelector(domCheckSelector) === null) {
  1607. return;
  1608. }
  1609. domCheckScheduled = true;
  1610.  
  1611. mutexForDOMMutations.lockWith(lockResolve => {
  1612. domCheckScheduled = false;
  1613.  
  1614. const newAnchors = document.querySelectorAll(domCheckSelector);
  1615. if (newAnchors.length === 0) {
  1616. lockResolve();
  1617. return;
  1618. }
  1619.  
  1620. const cNewAnchorFirst = newAnchors[0]; // non-null
  1621. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1622. /** @type {HTMLElement | null} */
  1623. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1624. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1625.  
  1626. if (!firstDOMCheck) {
  1627. firstDOMCheck = true;
  1628. USE_CHANNEL_META && firstDOMChecker();
  1629. }
  1630.  
  1631. Promise.resolve()
  1632. .then(() => {
  1633. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1634. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1635. mutex.nextIndex = 0;
  1636. }
  1637. }
  1638. }).then(() => {
  1639.  
  1640. // newAnchorAdded = true;
  1641. for (const anchor of newAnchors) {
  1642. // author-text or name
  1643. // normal url: /channel/xxxxxxx
  1644. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1645. const href = anchor.getAttribute('href');
  1646. const channelId = obtainChannelId(href); // string, can be empty
  1647. anchor.setAttribute('jkrgy', channelId);
  1648. // intersectionobserver.unobserve(anchor);
  1649. // intersectionobserver.observe(anchor); // force first occurance
  1650. domCheckAsync(anchor, href, channelId);
  1651. }
  1652.  
  1653. }).then(lockResolve).catch(e => {
  1654. lockResolve();
  1655. console.warn(e);
  1656. });
  1657.  
  1658. });
  1659.  
  1660.  
  1661. };
  1662.  
  1663.  
  1664. /** @type {MutationObserver | null} */
  1665. let domObserver = null;
  1666.  
  1667. /** @type {(callback: (event: Event)=>{})} */
  1668. const onPageFetched = isMobile ? (callback) => {
  1669.  
  1670. let state = 0;
  1671.  
  1672. window.addEventListener('state-change', function (evt) {
  1673. if (state === 1) return; // ignore intermediate events
  1674. state = 1; // before value: 0 or 2;
  1675. callback(evt);
  1676. }, false);
  1677.  
  1678. window.addEventListener('state-navigateend', function (evt) { // fallback
  1679. let inSeq = state === 1;
  1680. state = 2; // 2 when loaded
  1681. if (!inSeq) callback(evt);
  1682. }, false);
  1683.  
  1684. } : (callback) => {
  1685.  
  1686. let state = 0;
  1687.  
  1688. document.addEventListener('yt-page-data-fetched', function (evt) {
  1689. if (state === 1) return; // ignore intermediate events if any
  1690. state = 1; // before value: 0 or 2;
  1691. callback(evt);
  1692. }, false);
  1693.  
  1694. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1695. let inSeq = state === 1;
  1696. state = 2; // 2 when loaded
  1697. if (!inSeq) callback(evt);
  1698. }, false);
  1699.  
  1700. };
  1701.  
  1702. /**
  1703. *
  1704. * @param {Node} app
  1705. * @returns
  1706. */
  1707. function setupOnPageFetched(app) {
  1708.  
  1709. firstDOMCheck = false;
  1710.  
  1711. if (!cfg['INNERTUBE_API_KEY']) {
  1712. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1713. return;
  1714. }
  1715.  
  1716. if (CHANGE_FOR_SHORTS_CHANNEL_NAME && location.pathname.startsWith('/shorts/')) {
  1717. doShortsChecking = true;
  1718. } else {
  1719. doShortsChecking = false;
  1720. }
  1721.  
  1722. if (!domObserver) {
  1723. domObserver = new MutationObserver(domChecker);
  1724. } else {
  1725. domObserver.takeRecords();
  1726. domObserver.disconnect();
  1727. }
  1728.  
  1729. domObserver.observe(app, { childList: true, subtree: true });
  1730. domChecker();
  1731.  
  1732. }
  1733.  
  1734. /**
  1735. *
  1736. * @param {Object|null} dest
  1737. * @param {Object} ytcfg
  1738. * @param {string[]} keys
  1739. * @returns
  1740. */
  1741. function getYtConfig(dest, ytcfg, keys) {
  1742. dest = dest || {};
  1743. if (typeof ytcfg.get === 'function') { // mobile
  1744. for (const key of keys) {
  1745. dest[key] = ytcfg.get(key);
  1746. }
  1747. } else {
  1748. const cfgData = ytcfg.data_ || ytcfg.__data || ytcfg._data || ytcfg.data || ytcfg; // dekstop - ytcfg.data_
  1749. for (const key of keys) {
  1750. dest[key] = cfgData[key];
  1751. }
  1752. }
  1753. return dest;
  1754. }
  1755.  
  1756. /** @type { (evt: Object) => Element | null } */
  1757. const getPageApp = isMobile
  1758. ? ((evt) => (document.querySelector('ytm-app#app') || document.querySelector('ytm-app')))
  1759. : ((evt) => ((evt || 0).target || document.querySelector('ytd-app')));
  1760.  
  1761. onPageFetched(async (evt) => {
  1762. const app = getPageApp(evt);
  1763. console.assert(app);
  1764. const ytcfg = ((window || 0).ytcfg || 0);
  1765. getYtConfig(cfg, ytcfg, ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']);
  1766. setupOnPageFetched(app);
  1767. });
  1768.  
  1769. })({ fetch, JSON, Request, AbortController, setTimeout, clearTimeout });