Restore YouTube Username from Handle to Custom

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

当前为 2023-06-24 提交的版本,查看 最新版本

  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.5.13
  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 55
  45. // @compatible chrome 61
  46. // @compatible opera 48
  47. // @compatible safari 11.1
  48. // @compatible edge 16
  49.  
  50. // @description To restore YouTube Username to the traditional custom name
  51. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  52. // @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
  53. // @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
  54.  
  55. // @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
  56. // @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
  57. // @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
  58. // @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
  59. // @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
  60. // @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
  61. // @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
  62. // @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
  63. // @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
  64. // @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
  65. // @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
  66. // @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
  67. // @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
  68. // @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
  69. // @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
  70. // @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
  71. // @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
  72. // @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
  73. // @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
  74. // @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
  75. // @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
  76. // @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
  77. // @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
  78. // @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
  79. // @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
  80. // @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
  81. // @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
  82. // @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
  83. // @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
  84. // @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
  85. // @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
  86. // @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
  87. // @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
  88. // @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
  89. // @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
  90. // @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
  91. // @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
  92. // @description:tr Özel İsme Kullanıcı Adını İade Etme
  93. // @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
  94. // @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
  95. // @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
  96. // @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
  97. // @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
  98. // @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
  99. // @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
  100. // @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
  101. // @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
  102. // @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
  103. // @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
  104. // @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
  105. // @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
  106. // @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
  107. // @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
  108. // @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
  109. // @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
  110. // @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
  111. // @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
  112. // @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
  113. // @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
  114. // @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్‌కు పునరుద్ధరించండి
  115. // @description:kn ಹ್ಯಾಂಡಲ್‌ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
  116. // @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
  117. // @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
  118. // @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
  119. // @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
  120. // @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
  121. // @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
  122. // @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
  123. // @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
  124.  
  125. // ==/UserScript==
  126.  
  127. /* jshint esversion:8 */
  128.  
  129.  
  130. /**
  131. @typedef DisplayNameResultObject
  132. @type {Object}
  133. @property {string} title
  134. @property {string?} externalId
  135. @property {string[]} ownerUrls
  136. @property {string} channelUrl
  137. @property {string} vanityChannelUrl
  138. @property {boolean|undefined} verified123
  139.  
  140. */
  141.  
  142. (function (__CONTEXT__) {
  143. 'use strict';
  144.  
  145. const { Promise, fetch } = __CONTEXT__; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  146.  
  147.  
  148. /*
  149.  
  150.  
  151. init
  152.  
  153. initialdata
  154. state-progress
  155. state-responsereceived
  156. player-autonav-pause
  157. state-change
  158. state-navigateend
  159. player-initialized
  160. renderer-module-load-start
  161. video-data-change
  162. player-state-change
  163. updateui
  164. renderer-module-load-end -> channel owner DOM available
  165. player-autonav-pause
  166. updateui
  167. renderer-module-load-start
  168. updateui
  169. renderer-module-load-end
  170.  
  171.  
  172. playing
  173.  
  174. h5player.video-progress
  175. h5player.video-progress
  176. h5player.video-progress
  177. h5player.video-progress
  178. ...
  179.  
  180.  
  181.  
  182.  
  183. navigate new video
  184.  
  185. state-navigatestart
  186. state-change => channel owener DOM vanished
  187. state-progress
  188. ...
  189. h5player.player-state-change
  190. h5player.video-data-change
  191. h5player.player-state-change
  192. h5player.muted-autoplay-change
  193. h5player.volume-change
  194. h5player.video-data-change
  195. h5player.volume-change
  196. ...
  197.  
  198. state-progress
  199. ...
  200.  
  201. state-progress => channel owner DOM appear [just before state-responsereceived]
  202. state-responsereceived
  203.  
  204. video-data-change
  205. state-change
  206. state-navigateend
  207.  
  208.  
  209.  
  210.  
  211. UX interaction
  212.  
  213. user-activity
  214. player-autonav-pause
  215.  
  216.  
  217.  
  218.  
  219.  
  220. EventTarget.prototype.uhfsE = EventTarget.prototype.dispatchEvent
  221.  
  222. EventTarget.prototype.dispatchEvent = function (ev) {
  223. if (ev instanceof Event) {
  224. if (ev.type === 'video-progress') { } else {
  225. console.log(ev.type, this, ev.target)
  226. if (ev.target === null) {
  227. console.log(ev.type, (document.querySelector('ytm-app') || 0).data)
  228. console.log(ev.type, (document.querySelector('ytm-slim-owner-renderer') || 0).textContent)
  229. }
  230. }
  231. }
  232. return this.uhfsE.apply(this, arguments);
  233. }
  234.  
  235.  
  236.  
  237. */
  238.  
  239. const isMobile = location.hostname === 'm.youtube.com';
  240.  
  241. const cfg = {};
  242. class Mutex {
  243.  
  244. constructor() {
  245. this.p = Promise.resolve()
  246. }
  247.  
  248. /**
  249. * @param {(lockResolve: () => void)} f
  250. */
  251. lockWith(f) {
  252. this.p = this.p.then(() => new Promise(f).catch(console.warn))
  253. }
  254.  
  255. }
  256.  
  257. class OrderedMutex extends Mutex {
  258. constructor() {
  259. super();
  260. this.nextIndex = 0;
  261. this.arr = [];
  262. this.lockFunc = resolve => {
  263. if (this.arr.length >= 1) {
  264. let f = this.arr[0];
  265. if (typeof f === 'function') {
  266. this.arr.shift();
  267. if (this.nextIndex > 0) this.nextIndex--;
  268. f(resolve);
  269. return;
  270. } else {
  271. // reset if unknown error
  272. this.arr.length = 0;
  273. this.nextIndex = 0;
  274. }
  275. }
  276. resolve();
  277. };
  278. }
  279. /**
  280. * @param {(lockResolve: () => void)} f
  281. */
  282. add(f) {
  283. if (this.nextIndex === this.arr.length) {
  284. this.arr.push(f); this.nextIndex++;
  285. } else {
  286. this.arr.splice(this.nextIndex++, 0, f);
  287. }
  288. this.lockWith(this.lockFunc);
  289. }
  290. }
  291. const mutex = new OrderedMutex();
  292.  
  293. /** @type {Map<string, AsyncValue | Object>} */
  294. const displayNameResStore = new Map();
  295.  
  296. /** @type {WeakMap<Function, Function>} */
  297. const dataChangedFuncStore = new WeakMap();
  298.  
  299. /** @type {Map<string, string>} */
  300. const handleToChannelId = new Map();
  301.  
  302. class AsyncValue {
  303. constructor() {
  304. this.__value__ = null;
  305. this.__resolve__ = null;
  306. this.__promise__ = new Promise(resolve => {
  307. this.__resolve__ = resolve;
  308. });
  309. }
  310. setValue(value) {
  311. const promise = this.__promise__;
  312. if (promise === null) throw 'Value has already been set.';
  313. this.__value__ = value;
  314. this.__promise__ = null;
  315. this.__resolve__ ? this.__resolve__() : Promise.resolve().then(() => this.__resolve__());
  316. }
  317. async getValue() {
  318. const promise = this.__promise__;
  319. if (promise === null) return this.__value__;
  320. await promise; // promise become null
  321. this.__promise__ = null; // just in case
  322. this.__resolve__ = null;
  323. return this.__value__;
  324. }
  325. }
  326.  
  327. /**
  328. *
  329. * @param {DisplayNameResultObject} resultInfo
  330. * @param {string} channelId
  331. */
  332. const cacheHandleToChannel = (resultInfo, channelId) => {
  333.  
  334. const { vanityChannelUrl, ownerUrls } = resultInfo;
  335.  
  336. let handleText = urlToHandle(vanityChannelUrl || '');
  337.  
  338. if (handleText) {
  339. // match = true;
  340. } else if ((ownerUrls || 0).length >= 1) {
  341. for (const ownerUrl of ownerUrls) {
  342. handleText = urlToHandle(ownerUrl || '');
  343.  
  344. if (handleText) {
  345. // match = true;
  346. break;
  347. }
  348. }
  349. }
  350. if (handleText) {
  351.  
  352. const asyncValue = handleToChannelId.get(handleText); // nothing if no pending promise
  353. if (asyncValue instanceof AsyncValue) {
  354. asyncValue.setValue(channelId);
  355. }
  356. handleToChannelId.set(handleText, channelId);
  357. }
  358.  
  359.  
  360. }
  361.  
  362. /**
  363. *
  364. * @param {string} channelId
  365. */
  366. function stackNewRequest(channelId) {
  367.  
  368. mutex.add(lockResolve => {
  369.  
  370. let bResult = displayNameResStore.get(channelId);
  371. if (!(bResult instanceof AsyncValue)) {
  372. // resolved or removed
  373. lockResolve(); lockResolve = null;
  374. return;
  375. }
  376.  
  377. let setResult = (result) => {
  378. setResult = null;
  379. if (!result) {
  380. bResult.fetchingState = 0;
  381. bResult.setValue(null);
  382. displayNameResStore.delete(channelId); // create another network response in the next request
  383. } else {
  384. bResult.fetchingState = 4;
  385. bResult.setValue(result);
  386. displayNameResStore.set(channelId, result); // update store result to resolved value
  387. }
  388. bResult = null;
  389. }
  390.  
  391. if (bResult.fetchingState >= 2) { // fetchingState == 3 or 4
  392. // request is already done. no need to stack any request
  393. lockResolve(); lockResolve = null;
  394. return;
  395. }
  396.  
  397. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  398. // element has already been removed
  399. lockResolve(); lockResolve = null;
  400. setResult(null);
  401. return;
  402. }
  403.  
  404. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  405.  
  406. bResult.fetchingState = 2;
  407.  
  408. fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  409. "method": "POST",
  410. "mode": "same-origin",
  411. "credentials": "same-origin",
  412.  
  413. referrerPolicy: "no-referrer",
  414. cache: "default",
  415. redirect: "error", // there shall be no redirection in this API request
  416. integrity: "",
  417. keepalive: false,
  418. signal: undefined,
  419.  
  420. "headers": {
  421. "Content-Type": "application/json",
  422. "Accept-Encoding": "gzip, deflate, br",
  423. // X-Youtube-Bootstrap-Logged-In: false,
  424. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  425. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  426. },
  427. "body": JSON.stringify({
  428. "context": {
  429. "client": {
  430. "clientName": "MWEB",
  431. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  432. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  433. "playerType": "UNIPLAYER",
  434. "platform": "MOBILE",
  435. "clientFormFactor": "SMALL_FORM_FACTOR",
  436. "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",
  437. "mainAppWebInfo": {
  438. "graftUrl": `/channel/${channelId}`,
  439. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  440. "isWebNativeShareAvailable": true
  441. }
  442. },
  443. "user": {
  444. "lockedSafetyMode": false
  445. },
  446. "request": {
  447. "useSsl": true,
  448. "internalExperimentFlags": [],
  449. "consistencyTokenJars": []
  450. }
  451. },
  452. "browseId": `${channelId}`
  453. })
  454. })).then(res => {
  455. bResult.fetchingState = 3;
  456. lockResolve();
  457. lockResolve = null;
  458. return res.json();
  459. }).then(res => {
  460.  
  461. // console.log(displayNameRes, urlToHandle(vanityChannelUrl))
  462. // displayNameCacheStore.set(channelId, displayNameRes);
  463.  
  464.  
  465. let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  466. if (!resultInfo) {
  467. // invalid json format
  468. setResult(null);
  469. return;
  470. }
  471.  
  472. cacheHandleToChannel(resultInfo, channelId);
  473.  
  474. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = resultInfo;
  475.  
  476. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123: false };
  477.  
  478. setResult(displayNameRes);
  479.  
  480.  
  481. }).catch(e => {
  482. lockResolve && lockResolve();
  483. console.warn(e);
  484. setResult && setResult(null);
  485. });
  486.  
  487. });
  488.  
  489. }
  490.  
  491. /**
  492. *
  493. * @param {string} url Example: _www\.youtube\.com/\@yr__kd_
  494. * @returns Example: _\@yr__kd_
  495. */
  496. function urlToHandle(url) {
  497.  
  498. if (typeof url !== 'string') return '';
  499. let i = url.indexOf('.youtube.com/');
  500. if (i >= 1) url = url.substring(i + '.youtube.com/'.length);
  501. else if (url.charAt(0) === '/') url = url.substring(1);
  502. return isDisplayAsHandle(url) ? url : '';
  503.  
  504. }
  505.  
  506. /**
  507. *
  508. * @param {string} channelId Example: UC0gmRdmpDWJ4dt7DAeRaawA
  509. * @returns
  510. */
  511. function getDisplayName(channelId) {
  512.  
  513. return new Promise(resolve => {
  514.  
  515. let aResult = displayNameResStore.get(channelId);
  516. let isStackNewRequest = true;
  517.  
  518. if (aResult instanceof AsyncValue) {
  519.  
  520. if (aResult.fetchingState >= 2) {
  521. // aResult.fetchingState
  522. // 2: network fetch started
  523. // 3: network fetch ended
  524. isStackNewRequest = false;
  525. } else {
  526. // 0: invalid before
  527. // 1: scheduled but not yet fetch
  528. }
  529.  
  530. } else if (aResult) {
  531. // resolved result
  532. resolve(aResult);
  533. return;
  534. } else {
  535. // else no cached value found
  536. aResult = new AsyncValue();
  537. displayNameResStore.set(channelId, aResult);
  538. }
  539.  
  540. /** @type {AsyncValue} */
  541. const bResult = aResult;
  542.  
  543. bResult.getValue().then(resolve);
  544. if (isStackNewRequest) {
  545. bResult.fetchingState = 1;
  546. stackNewRequest(channelId);
  547. }
  548. }).catch(console.warn);
  549. }
  550.  
  551.  
  552. /**
  553. *
  554. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  555. * @returns
  556. */
  557. const obtainChannelId = (href) => {
  558. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  559. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  560. return !m ? '' : (m[1] || '');
  561. };
  562.  
  563. /**
  564. *
  565. * @param {Function} dataChanged original dataChanged function
  566. * @returns new dataChanged function
  567. */
  568. const dataChangeFuncProducer = (dataChanged) => {
  569.  
  570. return function () {
  571. let anchors = null;
  572. try {
  573. anchors = HTMLElement.prototype.querySelectorAll.call(this, 'a[id][href*="channel/"][jkrgy]');
  574. } catch (e) { }
  575. if ((anchors || 0).length >= 1 && (this.data || 0).jkrgx !== 1) {
  576. for (const anchor of anchors) {
  577. anchor.removeAttribute('jkrgy');
  578. }
  579. }
  580. return dataChanged.apply(this, arguments)
  581. }
  582.  
  583.  
  584. };
  585.  
  586. /**
  587. *
  588. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  589. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  590. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  591. * @returns
  592. */
  593. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  594.  
  595. let currentHref = anchor.getAttribute('href');
  596. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  597.  
  598. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  599.  
  600. };
  601.  
  602. /**
  603. *
  604. * @param {string} currentDisplayed
  605. * @param {DisplayNameResultObject} fetchResult
  606. * @returns
  607. */
  608. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  609.  
  610. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  611.  
  612. const currentDisplayTrimmed = currentDisplayed.trim();
  613. let match = false;
  614. if (verified123) {
  615. match = true;
  616. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  617. match = true;
  618. } else if ((ownerUrls || 0).length >= 1) {
  619. for (const ownerUrl of ownerUrls) {
  620. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  621. match = true;
  622. break;
  623. }
  624. }
  625. }
  626. if (match) {
  627. return currentDisplayTrimmed;
  628. }
  629. return '';
  630.  
  631. };
  632.  
  633. /**
  634. *
  635. *
  636.  
  637. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  638.  
  639. - Is between 3-30 characters
  640. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  641. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  642. - Is not URL-like or phone number-like
  643. - Is not already being used
  644. - Follows YouTube's Community Guidelines
  645.  
  646. ### Handle automatically generated by YouTube
  647. - `@user-XXXX`
  648. - without dot (.)
  649. *
  650. * @param {string} text
  651. * @returns
  652. */
  653. const isDisplayAsHandle = (text) => {
  654.  
  655. if (typeof text !== 'string') return false;
  656. if (text.length < 4) return false;
  657. if (text.indexOf('@') < 0) return false;
  658. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  659.  
  660. };
  661.  
  662. /**
  663. *
  664. * @param {Object[]} contentTexts
  665. * @param {number} idx
  666. * @returns
  667. */
  668. const contentTextProcess = (contentTexts, idx) => {
  669. const contentText = contentTexts[idx];
  670. const text = (contentText || 0).text;
  671. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  672. if (typeof url === 'string' && typeof text === 'string') {
  673.  
  674. if (!isDisplayAsHandle(text)) return null;
  675. const channelId = obtainChannelId(url);
  676.  
  677. return getDisplayName(channelId).then(fetchResult => {
  678. let resolveResult = null;
  679. if (fetchResult) {
  680. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  681.  
  682. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  683. if (textTrimmed) {
  684. resolveResult = (md) => {
  685. let runs = ((md || 0).contentText || 0).runs;
  686. if (!runs || !runs[idx]) return;
  687. if (runs[idx].text !== text) return;
  688. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  689. md.contentText = Object.assign({}, md.contentText);
  690. };
  691. }
  692. }
  693. return (resolveResult); // function as a Promise
  694. });
  695. }
  696.  
  697. return null;
  698. };
  699.  
  700. /**
  701. *
  702. * @param {ParentNode} parentNode
  703. * @param {Function} callback
  704. */
  705. function findTextNodes(parentNode, callback) {
  706. /**
  707. *
  708. * @param {Node} node
  709. * @returns
  710. */
  711. function traverse(node) {
  712. if (node.nodeType === Node.TEXT_NODE) {
  713. let r = callback(node);
  714. if (r === true) return true;
  715. }
  716.  
  717. let childNode = node.firstChild;
  718. while (childNode) {
  719. let r = traverse(childNode);
  720. if (r === true) return true;
  721. childNode = childNode.nextSibling;
  722. }
  723. }
  724.  
  725. traverse(parentNode);
  726. }
  727.  
  728. /**
  729. *
  730. * @param {ParentNode} parentNode
  731. * @param {Object[]} contentTexts
  732. * @param {number} aidx
  733. * @returns
  734. */
  735. const mobileContentHandle = async (parentNode, contentTexts, aidx) => {
  736.  
  737.  
  738. let commentText = parentNode.querySelector('.comment-text');
  739. if (!commentText) return;
  740. commentText = commentText.querySelector('.yt-core-attributed-string') || commentText
  741. let currentText = commentText.textContent;
  742. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  743. if (!textMatch) return;
  744.  
  745. let handleText = contentTexts[aidx].text.trim();
  746. let channelId;
  747.  
  748. let cache = handleToChannelId.get(handleText);
  749.  
  750. if (typeof cache === 'string') {
  751. channelId = cache;
  752. } else if (cache instanceof AsyncValue) {
  753. channelId = await cache.getValue();
  754. } else {
  755. const asyncValue = new AsyncValue();
  756. handleToChannelId.set(handleText, asyncValue);
  757. channelId = await asyncValue.getValue(); // note: it could be never resolved
  758. }
  759.  
  760. if (!channelId) return; // just in case
  761.  
  762. if (commentText.isConnected !== true) return; // already removed
  763. if (commentText.textContent !== currentText) return; // already changed
  764.  
  765. const fetchResult = await getDisplayName(channelId);
  766.  
  767. if (fetchResult === null) return;
  768.  
  769. const { title, externalId } = fetchResult;
  770. if (externalId !== channelId) return; // channel id must be the same
  771.  
  772. let search = contentTexts[aidx].text;
  773. if (typeof search === 'string') {
  774.  
  775. contentTexts[aidx].text = search.replace(search.trim(), "@" + title);
  776.  
  777. findTextNodes(commentText, (textnode) => {
  778. if (textnode.nodeValue.indexOf(search) >= 0) {
  779. textnode.nodeValue = textnode.nodeValue.replace(search, contentTexts[aidx].text);
  780. return true;
  781. }
  782. });
  783.  
  784. }
  785.  
  786. }
  787.  
  788. /**
  789. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  790. * @type {(anchor: HTMLElement, channelHref: string?, mt: string?)}
  791. */
  792. const domCheck = isMobile ? async (anchor, channelHref, mt) => {
  793.  
  794. if (!channelHref || !mt) return;
  795. let parentNode = anchor.parentNode;
  796. while (parentNode instanceof Node) {
  797. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  798. parentNode = parentNode.parentNode
  799. }
  800. if (parentNode instanceof Node) { } else return;
  801.  
  802. let displayTextDOM = parentNode.querySelector('.comment-header .comment-title');
  803. if (!displayTextDOM) return;
  804. displayTextDOM = displayTextDOM.querySelector('.yt-core-attributed-string') || displayTextDOM;
  805. let airaLabel = anchor.getAttribute('aria-label')
  806. const parentNodeData = parentNode.data;
  807. let runs = ((parentNodeData || 0).authorText || 0).runs;
  808.  
  809. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  810.  
  811. const fetchResult = await getDisplayName(mt);
  812.  
  813. if (fetchResult === null) return;
  814.  
  815. const { title, externalId } = fetchResult;
  816.  
  817. if (externalId !== mt) return; // channel id must be the same
  818.  
  819. // anchor href might be changed by external
  820. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  821.  
  822. let found = false;
  823.  
  824. findTextNodes(displayTextDOM, (textnode) => {
  825. if (textnode.nodeValue === airaLabel) {
  826. textnode.nodeValue = title;
  827. found = true;
  828. return true;
  829. }
  830. });
  831.  
  832. if (!found) return;
  833. anchor.setAttribute('aria-label', title);
  834. runs[0].text = title;
  835.  
  836.  
  837. const contentTexts = (parentNodeData.contentText || 0).runs;
  838. if (contentTexts && contentTexts.length >= 2) {
  839. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  840. if (contentTexts[aidx].italics !== true) {
  841. let isHandle = isDisplayAsHandle(contentTexts[aidx].text);
  842. if (isHandle) {
  843. mobileContentHandle(parentNode, contentTexts, aidx);
  844. }
  845. }
  846. }
  847. }
  848.  
  849. }
  850.  
  851.  
  852. } : async (anchor, channelHref, mt) => {
  853.  
  854. try {
  855. if (!channelHref || !mt) return;
  856. let parentNode = anchor.parentNode;
  857. while (parentNode instanceof Node) {
  858. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  859. parentNode = parentNode.parentNode
  860. }
  861. if (parentNode instanceof Node) { } else return;
  862. const authorText = (parentNode.data || 0).authorText;
  863. const currentDisplayed = (authorText || 0).simpleText;
  864. if (typeof currentDisplayed !== 'string') return;
  865. if (!isDisplayAsHandle(currentDisplayed)) return;
  866.  
  867. const oldDataChanged = parentNode.dataChanged;
  868. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  869. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  870. if (!newDataChanged) {
  871. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  872. newDataChanged.jkrgx = 1;
  873. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  874. }
  875. parentNode.dataChanged = newDataChanged;
  876. }
  877.  
  878. const fetchResult = await getDisplayName(mt);
  879.  
  880. if (fetchResult === null) return;
  881.  
  882. const { title, externalId } = fetchResult;
  883.  
  884. if (externalId !== mt) return; // channel id must be the same
  885.  
  886. // anchor href might be changed by external
  887. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  888.  
  889. const parentNodeData = parentNode.data
  890. const funcPromises = [];
  891.  
  892. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  893.  
  894. if (authorText.simpleText !== currentDisplayed) return;
  895. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  896. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  897. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  898.  
  899. // the inside hyperlinks will be only converted if its parent author name is handle
  900. const contentTexts = (parentNodeData.contentText || 0).runs;
  901. if (contentTexts && contentTexts.length >= 1) {
  902. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  903. const r = contentTextProcess(contentTexts, aidx);
  904. if (r instanceof Promise) funcPromises.push(r);
  905. }
  906. }
  907.  
  908. const md = Object.assign({}, parentNodeData);
  909. let setBadge = false;
  910. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  911. setBadge = true;
  912. }
  913. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  914. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  915. if (setBadge) {
  916. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  917. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  918. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  919.  
  920. }
  921. if (funcPromises.length >= 1) {
  922. let funcs = await Promise.all(funcPromises);
  923.  
  924. for (const func of funcs) {
  925. if (typeof func === 'function') {
  926. func(md);
  927. }
  928. }
  929. }
  930. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  931. }
  932.  
  933. }
  934. } catch (e) {
  935. console.warn(e);
  936. }
  937.  
  938.  
  939. }
  940.  
  941. /**
  942. *
  943. * @param {string} url
  944. * @returns
  945. */
  946. const channelUrlUnify = (url) => {
  947.  
  948. if (typeof url !== 'string') return url; // type unchanged
  949. let c0 = url.charAt(0);
  950. if (c0 === '/') return url;
  951. let i = url.indexOf('.youtube.com/');
  952. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  953. else if (url.charAt(0) !== '/') url = '/' + url;
  954. return url
  955.  
  956. }
  957.  
  958. let firstDOMCheck = false;
  959. const firstDOMChecker = isMobile ? () => {
  960.  
  961. let channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  962. let channelNameDOMData = (channelNameDOM || 0).data;
  963.  
  964. if (channelNameDOMData) {
  965. let mainChannelUrl = null;
  966. let mainFormattedNameUrl = null;
  967. let mainChannelText = null;
  968. let mainFormattedNameText = null;
  969.  
  970. try {
  971. mainChannelUrl = channelUrlUnify(channelNameDOMData.channelUrl)
  972. mainFormattedNameUrl = channelUrlUnify(channelNameDOMData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  973. mainChannelText = channelNameDOMData.channelName
  974. mainFormattedNameText = channelNameDOMData.title.runs[0].text
  975. } catch (e) { }
  976.  
  977. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  978.  
  979.  
  980. let channelId = obtainChannelId(mainChannelUrl);
  981. if (channelId) {
  982. if (mainChannelText.startsWith('@')) return;
  983. if (mainChannelText.trim() !== mainChannelText) return;
  984.  
  985. displayNameResStore.set(channelId, {
  986. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  987. externalId: `${channelId}`,
  988. ownerUrls: [],
  989. title: mainChannelText,
  990. vanityChannelUrl: null,
  991. verified123: true
  992. });
  993. }
  994.  
  995.  
  996. }
  997. }
  998.  
  999. } : () => {
  1000.  
  1001. let channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1002. let channelNameDOMData = (channelNameDOM || 0).__data;
  1003. if (channelNameDOMData) {
  1004. let mainChannelUrl = null;
  1005. let mainFormattedNameUrl = null;
  1006. let mainChannelText = null;
  1007. let mainFormattedNameText = null;
  1008.  
  1009. try {
  1010. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1011. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1012. mainChannelText = channelNameDOMData.channelName.runs[0].text
  1013. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  1014. } catch (e) { }
  1015.  
  1016. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1017.  
  1018. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.test(mainChannelUrl);
  1019.  
  1020. if (m && m[1] && mainChannelText !== m[1]) {
  1021.  
  1022. let channelId = obtainChannelId(mainChannelUrl);
  1023. if (channelId) {
  1024. if (mainChannelText.startsWith('@')) return;
  1025. if (mainChannelText.trim() !== mainChannelText) return;
  1026.  
  1027. displayNameResStore.set(channelId, {
  1028. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1029. externalId: `${channelId}`,
  1030. ownerUrls: [],
  1031. title: mainChannelText,
  1032. vanityChannelUrl: null,
  1033. verified123: true
  1034. });
  1035. }
  1036.  
  1037. }
  1038. }
  1039. }
  1040.  
  1041.  
  1042.  
  1043.  
  1044. };
  1045.  
  1046. // let newAnchorAdded = false;
  1047. /*
  1048.  
  1049. const intersectionobserver = new IntersectionObserver((entries) => {
  1050. let anchorAppear = false;
  1051. for (const entry of entries) {
  1052. if (entry.isIntersecting === true) {
  1053. anchorAppear = true;
  1054. break;
  1055. }
  1056. }
  1057. if (anchorAppear && newAnchorAdded) {
  1058. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1059. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1060. }
  1061. }, {
  1062. rootMargin:"0px 0px 0px 0px",
  1063. threshold:1
  1064. })
  1065. */
  1066.  
  1067.  
  1068. /* globals WeakRef:false */
  1069.  
  1070. /** @type {(o: Object | null) => WeakRef | null} */
  1071. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1072.  
  1073. /** @type {(wr: Object | null) => Object | null} */
  1074. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1075.  
  1076. let lastNewAnchorLastWR = null;
  1077.  
  1078. let domCheckTimeStamp = 0;
  1079.  
  1080. const mutexForDOMMutations = new Mutex();
  1081. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]' : 'a[id][href*="channel/"]:not([jkrgy])';
  1082.  
  1083. const domChecker = () => {
  1084.  
  1085. const newAnchors = document.querySelectorAll(domCheckSelector);
  1086. if (newAnchors.length === 0) {
  1087. return;
  1088. }
  1089.  
  1090. mutexForDOMMutations.lockWith(lockResolve => {
  1091.  
  1092. const newAnchors = document.querySelectorAll(domCheckSelector);
  1093. if (newAnchors.length === 0) {
  1094. lockResolve();
  1095. return;
  1096. }
  1097.  
  1098. const cNewAnchorFirst = newAnchors[0]; // non-null
  1099. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1100. /** @type {HTMLElement | null} */
  1101. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1102. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1103.  
  1104. const ltDOMCheck = domCheckTimeStamp;
  1105. const ctDOMCheck = Date.now();
  1106. domCheckTimeStamp = ctDOMCheck;
  1107.  
  1108. if (!firstDOMCheck) {
  1109. firstDOMCheck = true;
  1110. firstDOMChecker();
  1111. }
  1112.  
  1113. new Promise(resolve => {
  1114. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1115.  
  1116. if (ctDOMCheck - ltDOMCheck < 230) {
  1117.  
  1118. } else {
  1119. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1120. mutex.nextIndex = 0;
  1121. }
  1122. }
  1123.  
  1124. /*
  1125. if (mutex.nextIndex === 0) {
  1126. // no change
  1127. } else if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorLast) & 2) === 2) { // when "XX replies" clicked
  1128. mutex.nextIndex = 0; // highest priority
  1129. } else if (cNewAnchorLast !== cNewAnchorFirst && (lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 1) { // rarely
  1130. mutex.nextIndex = Math.floor(mutex.nextIndex / 2); // relatively higher priority
  1131. }
  1132. */
  1133. }
  1134. resolve();
  1135. }).then(() => {
  1136.  
  1137. // newAnchorAdded = true;
  1138. for (const anchor of newAnchors) {
  1139. // author-text or name
  1140. // normal url: /channel/xxxxxxx
  1141. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1142. const href = anchor.getAttribute('href');
  1143. const channelId = obtainChannelId(href); // string, can be empty
  1144. anchor.setAttribute('jkrgy', channelId);
  1145. // intersectionobserver.unobserve(anchor);
  1146. // intersectionobserver.observe(anchor); // force first occurance
  1147. domCheck(anchor, href, channelId);
  1148. }
  1149.  
  1150. }).then(lockResolve).catch(e => {
  1151. lockResolve();
  1152. console.warn(e);
  1153. });
  1154.  
  1155. });
  1156.  
  1157.  
  1158. };
  1159.  
  1160.  
  1161. /** @type {MutationObserver | null} */
  1162. let domObserver = null;
  1163.  
  1164. const onPageFetched = isMobile ? (callback, final) => {
  1165.  
  1166. let state = 0;
  1167.  
  1168. window.addEventListener('state-change', function (evt) {
  1169. if (state === 1) return; // ignore intermediate events
  1170. state = 1; // before value: 0 or 2;
  1171. callback(evt);
  1172. }, false);
  1173.  
  1174. window.addEventListener('state-navigateend', function (evt) { // fallback
  1175. let inSeq = state === 1;
  1176. state = 2; // 2 when loaded
  1177. if (!inSeq) callback(evt);
  1178. }, false);
  1179.  
  1180. } : (callback) => {
  1181.  
  1182. let state = 0;
  1183.  
  1184. document.addEventListener('yt-page-data-fetched', function (evt) {
  1185. if (state === 1) return; // ignore intermediate events if any
  1186. state = 1; // before value: 0 or 2;
  1187. callback(evt);
  1188. }, false);
  1189.  
  1190. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1191. let inSeq = state === 1;
  1192. state = 2; // 2 when loaded
  1193. if (!inSeq) callback(evt);
  1194. }, false);
  1195.  
  1196. };
  1197.  
  1198. /**
  1199. *
  1200. * @param {Node} app
  1201. * @returns
  1202. */
  1203. function setupOnPageFetched(app) {
  1204.  
  1205. firstDOMCheck = false;
  1206.  
  1207. if (!cfg['INNERTUBE_API_KEY']) {
  1208. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1209. return;
  1210. }
  1211.  
  1212. if (!domObserver) {
  1213. domObserver = new MutationObserver(domChecker);
  1214. } else {
  1215. domObserver.takeRecords();
  1216. domObserver.disconnect();
  1217. }
  1218.  
  1219. domObserver.observe(app, { childList: true, subtree: true });
  1220. domChecker();
  1221.  
  1222. }
  1223.  
  1224. if (isMobile) {
  1225.  
  1226. onPageFetched(async (evt) => {
  1227. let app = document.querySelector('ytm-app#app') || document.querySelector('ytm-app');
  1228. console.assert(app);
  1229. const ytcfg = ((window || 0).ytcfg || 0);
  1230. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  1231. cfg[key] = ytcfg.get(key);
  1232. }
  1233. setupOnPageFetched(app);
  1234. });
  1235.  
  1236. } else {
  1237.  
  1238. onPageFetched(async (evt) => {
  1239. const app = (evt || 0).target || document.querySelector('ytd-app');
  1240. console.assert(app);
  1241. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  1242. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  1243. cfg[key] = cfgData[key];
  1244. }
  1245. setupOnPageFetched(app);
  1246. });
  1247.  
  1248. }
  1249.  
  1250. })({ Promise, fetch });