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, AsyncValue | 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 {Promise<DisplayNameResultObject | null>}
  510. */
  511. async function getDisplayName(channelId) {
  512.  
  513. let cache = displayNameResStore.get(channelId);
  514. let isStackNewRequest = false;
  515.  
  516. /** @type {AsyncValue | null | undefined} */
  517. let aResult;
  518.  
  519. if (cache instanceof AsyncValue) {
  520. aResult = cache;
  521. if (aResult.fetchingState >= 2) {
  522. // aResult.fetchingState
  523. // 2: network fetch started
  524. // 3: network fetch ended
  525. // isStackNewRequest = false;
  526. } else {
  527. // 0: invalid before
  528. // 1: scheduled but not yet fetch
  529. isStackNewRequest = true;
  530. }
  531. } else if (cache) {
  532. // resolved result
  533. return cache;
  534. } else {
  535. // else no cached value found
  536. aResult = new AsyncValue();
  537. displayNameResStore.set(channelId, aResult);
  538. isStackNewRequest = true;
  539. }
  540.  
  541. if (isStackNewRequest) {
  542. aResult.fetchingState = 1;
  543. stackNewRequest(channelId);
  544. }
  545. return await aResult.getValue();
  546. }
  547.  
  548.  
  549. /**
  550. *
  551. * @param {string} href Example: https\:\/\/www\.youtube\.com/channel/UC0gmRdmpDWJ4dt7DAeRaawA
  552. * @returns
  553. */
  554. const obtainChannelId = (href) => {
  555. let m = /\/channel\/(UC[-_a-zA-Z0-9+=.]+)/.exec(`/${href}`);
  556. // let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  557. return !m ? '' : (m[1] || '');
  558. };
  559.  
  560. /**
  561. *
  562. * @param {Function} dataChanged original dataChanged function
  563. * @returns new dataChanged function
  564. */
  565. const dataChangeFuncProducer = (dataChanged) => {
  566.  
  567. return function () {
  568. let anchors = null;
  569. try {
  570. anchors = HTMLElement.prototype.querySelectorAll.call(this, 'a[id][href*="channel/"][jkrgy]');
  571. } catch (e) { }
  572. if ((anchors || 0).length >= 1 && (this.data || 0).jkrgx !== 1) {
  573. for (const anchor of anchors) {
  574. anchor.removeAttribute('jkrgy');
  575. }
  576. }
  577. return dataChanged.apply(this, arguments)
  578. }
  579.  
  580.  
  581. };
  582.  
  583. /**
  584. *
  585. * @param {HTMLAnchorElement} anchor Example: https\:\/\/www\.youtube\.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos
  586. * @param {string} channelHref Example: /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  587. * @param {string} channelId Example: UCRmLncxsQFcOOC8OhzUIfxQ
  588. * @returns
  589. */
  590. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  591.  
  592. let currentHref = anchor.getAttribute('href');
  593. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  594.  
  595. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  596.  
  597. };
  598.  
  599. /**
  600. *
  601. * @param {string} currentDisplayed
  602. * @param {DisplayNameResultObject} fetchResult
  603. * @returns
  604. */
  605. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  606.  
  607. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified123 } = fetchResult;
  608.  
  609. const currentDisplayTrimmed = currentDisplayed.trim();
  610. let match = false;
  611. if (verified123) {
  612. match = true;
  613. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  614. match = true;
  615. } else if ((ownerUrls || 0).length >= 1) {
  616. for (const ownerUrl of ownerUrls) {
  617. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  618. match = true;
  619. break;
  620. }
  621. }
  622. }
  623. if (match) {
  624. return currentDisplayTrimmed;
  625. }
  626. return '';
  627.  
  628. };
  629.  
  630. /**
  631. *
  632. *
  633.  
  634. ### [Handle naming guidelines](https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid)
  635.  
  636. - Is between 3-30 characters
  637. - Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  638. - Your handle can also include: underscores (_), hyphens (-), dots (.)
  639. - Is not URL-like or phone number-like
  640. - Is not already being used
  641. - Follows YouTube's Community Guidelines
  642.  
  643. ### Handle automatically generated by YouTube
  644. - `@user-XXXX`
  645. - without dot (.)
  646. *
  647. * @param {string} text
  648. * @returns
  649. */
  650. const isDisplayAsHandle = (text) => {
  651.  
  652. if (typeof text !== 'string') return false;
  653. if (text.length < 4) return false;
  654. if (text.indexOf('@') < 0) return false;
  655. return /^\s*@[-_a-zA-Z0-9.]{3,30}\s*$/.test(text);
  656.  
  657. };
  658.  
  659. /**
  660. *
  661. * @param {Object[]} contentTexts
  662. * @param {number} idx
  663. * @returns
  664. */
  665. const contentTextProcess = (contentTexts, idx) => {
  666. const contentText = contentTexts[idx];
  667. const text = (contentText || 0).text;
  668. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  669. if (typeof url === 'string' && typeof text === 'string') {
  670.  
  671. if (!isDisplayAsHandle(text)) return null;
  672. const channelId = obtainChannelId(url);
  673.  
  674. return getDisplayName(channelId).then(fetchResult => {
  675. let resolveResult = null;
  676. if (fetchResult) {
  677. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  678.  
  679. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  680. if (textTrimmed) {
  681. resolveResult = (md) => {
  682. let runs = ((md || 0).contentText || 0).runs;
  683. if (!runs || !runs[idx]) return;
  684. if (runs[idx].text !== text) return;
  685. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  686. md.contentText = Object.assign({}, md.contentText);
  687. };
  688. }
  689. }
  690. return (resolveResult); // function as a Promise
  691. });
  692. }
  693.  
  694. return null;
  695. };
  696.  
  697. /**
  698. *
  699. * @param {ParentNode} parentNode
  700. * @param {Function} callback
  701. */
  702. function findTextNodes(parentNode, callback) {
  703. /**
  704. *
  705. * @param {Node} node
  706. * @returns
  707. */
  708. function traverse(node) {
  709. if (node.nodeType === Node.TEXT_NODE) {
  710. let r = callback(node);
  711. if (r === true) return true;
  712. }
  713.  
  714. let childNode = node.firstChild;
  715. while (childNode) {
  716. let r = traverse(childNode);
  717. if (r === true) return true;
  718. childNode = childNode.nextSibling;
  719. }
  720. }
  721.  
  722. traverse(parentNode);
  723. }
  724.  
  725. /**
  726. *
  727. * @param {ParentNode} parentNode
  728. * @param {Object[]} contentTexts
  729. * @param {number} aidx
  730. * @returns
  731. */
  732. const mobileContentHandle = async (parentNode, contentTexts, aidx) => {
  733.  
  734.  
  735. let commentText = parentNode.querySelector('.comment-text');
  736. if (!commentText) return;
  737. commentText = commentText.querySelector('.yt-core-attributed-string') || commentText
  738. let currentText = commentText.textContent;
  739. let textMatch = commentText.textContent === contentTexts.map(e => e.text).join('');
  740. if (!textMatch) return;
  741.  
  742. const contentText = contentTexts[aidx];
  743.  
  744. /** @type {string} */
  745. const handleText = contentText.text.trim();
  746. /** @type {string | null | undefined} */
  747. let channelId;
  748.  
  749. let cache = handleToChannelId.get(handleText);
  750.  
  751. if (typeof cache === 'string') {
  752. channelId = cache;
  753. } else if (cache instanceof AsyncValue) {
  754. channelId = await cache.getValue();
  755. } else {
  756. const asyncValue = new AsyncValue();
  757. handleToChannelId.set(handleText, asyncValue);
  758. channelId = await asyncValue.getValue(); // note: it could be never resolved
  759. }
  760.  
  761. if (!channelId) return; // just in case
  762.  
  763. if (commentText.isConnected !== true) return; // already removed
  764. if (commentText.textContent !== currentText) return; // already changed
  765.  
  766. const fetchResult = await getDisplayName(channelId);
  767.  
  768. if (fetchResult === null) return;
  769.  
  770. const { title, externalId } = fetchResult;
  771. if (externalId !== channelId) return; // channel id must be the same
  772.  
  773. let search = contentText.text;
  774. if (typeof search === 'string') {
  775.  
  776. const searchTrimmed = search.trim();
  777. if (searchTrimmed === handleText) { // ensure integrity after getDisplayName
  778. contentText.text = search.replace(searchTrimmed, "@" + title);
  779.  
  780. findTextNodes(commentText, (textnode) => {
  781. if (textnode.nodeValue.indexOf(search) >= 0) {
  782. textnode.nodeValue = textnode.nodeValue.replace(search, contentText.text);
  783. return true;
  784. }
  785. });
  786. }
  787.  
  788. }
  789.  
  790. }
  791.  
  792. /**
  793. * Process Checking when there is new (unprocessed) anchor DOM element with hyperlink of channel
  794. * @type {(anchor: HTMLElement, channelHref: string?, mt: string?)}
  795. */
  796. const domCheck = isMobile ? async (anchor, channelHref, mt) => {
  797.  
  798. if (!channelHref || !mt) return;
  799. let parentNode = anchor.parentNode;
  800. while (parentNode instanceof Node) {
  801. if (parentNode.nodeName === 'YTM-COMMENT-RENDERER' || ('_commentData' in parentNode)) break;
  802. parentNode = parentNode.parentNode
  803. }
  804. if (parentNode instanceof Node) { } else return;
  805.  
  806. let displayTextDOM = parentNode.querySelector('.comment-header .comment-title');
  807. if (!displayTextDOM) return;
  808. displayTextDOM = displayTextDOM.querySelector('.yt-core-attributed-string') || displayTextDOM;
  809. let airaLabel = anchor.getAttribute('aria-label')
  810. const parentNodeData = parentNode.data;
  811. let runs = ((parentNodeData || 0).authorText || 0).runs;
  812.  
  813. if (displayTextDOM && airaLabel && displayTextDOM.textContent.trim() === airaLabel.trim() && isDisplayAsHandle(airaLabel) && runs && (runs[0] || 0).text === airaLabel) {
  814.  
  815. const fetchResult = await getDisplayName(mt);
  816.  
  817. if (fetchResult === null) return;
  818.  
  819. const { title, externalId } = fetchResult;
  820.  
  821. if (externalId !== mt) return; // channel id must be the same
  822.  
  823. // anchor href might be changed by external
  824. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  825.  
  826. let found = false;
  827.  
  828. findTextNodes(displayTextDOM, (textnode) => {
  829. if (textnode.nodeValue === airaLabel) {
  830. textnode.nodeValue = title;
  831. found = true;
  832. return true;
  833. }
  834. });
  835.  
  836. if (!found) return;
  837. anchor.setAttribute('aria-label', title);
  838. runs[0].text = title;
  839.  
  840.  
  841. const contentTexts = (parentNodeData.contentText || 0).runs;
  842. if (contentTexts && contentTexts.length >= 2) {
  843. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  844. if (contentTexts[aidx].italics !== true) {
  845. let isHandle = isDisplayAsHandle(contentTexts[aidx].text);
  846. if (isHandle) {
  847. mobileContentHandle(parentNode, contentTexts, aidx);
  848. }
  849. }
  850. }
  851. }
  852.  
  853. }
  854.  
  855.  
  856. } : async (anchor, channelHref, mt) => {
  857.  
  858. try {
  859. if (!channelHref || !mt) return;
  860. let parentNode = anchor.parentNode;
  861. while (parentNode instanceof Node) {
  862. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  863. parentNode = parentNode.parentNode
  864. }
  865. if (parentNode instanceof Node) { } else return;
  866. const authorText = (parentNode.data || 0).authorText;
  867. const currentDisplayed = (authorText || 0).simpleText;
  868. if (typeof currentDisplayed !== 'string') return;
  869. if (!isDisplayAsHandle(currentDisplayed)) return;
  870.  
  871. const oldDataChanged = parentNode.dataChanged;
  872. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  873. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  874. if (!newDataChanged) {
  875. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  876. newDataChanged.jkrgx = 1;
  877. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  878. }
  879. parentNode.dataChanged = newDataChanged;
  880. }
  881.  
  882. const fetchResult = await getDisplayName(mt);
  883.  
  884. if (fetchResult === null) return;
  885.  
  886. const { title, externalId } = fetchResult;
  887.  
  888. if (externalId !== mt) return; // channel id must be the same
  889.  
  890. // anchor href might be changed by external
  891. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  892.  
  893. const parentNodeData = parentNode.data
  894. const funcPromises = [];
  895.  
  896. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  897.  
  898. if (authorText.simpleText !== currentDisplayed) return;
  899. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  900. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  901. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  902.  
  903. // the inside hyperlinks will be only converted if its parent author name is handle
  904. const contentTexts = (parentNodeData.contentText || 0).runs;
  905. if (contentTexts && contentTexts.length >= 1) {
  906. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  907. const r = contentTextProcess(contentTexts, aidx);
  908. if (r instanceof Promise) funcPromises.push(r);
  909. }
  910. }
  911.  
  912. const md = Object.assign({}, parentNodeData);
  913. let setBadge = false;
  914. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  915. setBadge = true;
  916. }
  917. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  918. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  919. if (setBadge) {
  920. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  921. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  922. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  923.  
  924. }
  925. if (funcPromises.length >= 1) {
  926. let funcs = await Promise.all(funcPromises);
  927.  
  928. for (const func of funcs) {
  929. if (typeof func === 'function') {
  930. func(md);
  931. }
  932. }
  933. }
  934. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  935. }
  936.  
  937. }
  938. } catch (e) {
  939. console.warn(e);
  940. }
  941.  
  942.  
  943. }
  944.  
  945. /**
  946. *
  947. * @param {string} url
  948. * @returns
  949. */
  950. const channelUrlUnify = (url) => {
  951.  
  952. if (typeof url !== 'string') return url; // type unchanged
  953. let c0 = url.charAt(0);
  954. if (c0 === '/') return url;
  955. let i = url.indexOf('.youtube.com/');
  956. if (i >= 1) url = url.substring(i + '.youtube.com/'.length - 1);
  957. else if (url.charAt(0) !== '/') url = '/' + url;
  958. return url
  959.  
  960. }
  961.  
  962. let firstDOMCheck = false;
  963. const firstDOMChecker = isMobile ? () => {
  964.  
  965. let channelNameDOM = document.querySelector('ytm-slim-owner-renderer');
  966. let channelNameDOMData = (channelNameDOM || 0).data;
  967.  
  968. if (channelNameDOMData) {
  969. let mainChannelUrl = null;
  970. let mainFormattedNameUrl = null;
  971. let mainChannelText = null;
  972. let mainFormattedNameText = null;
  973.  
  974. try {
  975. mainChannelUrl = channelUrlUnify(channelNameDOMData.channelUrl)
  976. mainFormattedNameUrl = channelUrlUnify(channelNameDOMData.title.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl)
  977. mainChannelText = channelNameDOMData.channelName
  978. mainFormattedNameText = channelNameDOMData.title.runs[0].text
  979. } catch (e) { }
  980.  
  981. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  982.  
  983.  
  984. let channelId = obtainChannelId(mainChannelUrl);
  985. if (channelId) {
  986. if (mainChannelText.startsWith('@')) return;
  987. if (mainChannelText.trim() !== mainChannelText) return;
  988.  
  989. displayNameResStore.set(channelId, {
  990. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  991. externalId: `${channelId}`,
  992. ownerUrls: [],
  993. title: mainChannelText,
  994. vanityChannelUrl: null,
  995. verified123: true
  996. });
  997. }
  998.  
  999.  
  1000. }
  1001. }
  1002.  
  1003. } : () => {
  1004.  
  1005. let channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  1006. let channelNameDOMData = (channelNameDOM || 0).__data;
  1007. if (channelNameDOMData) {
  1008. let mainChannelUrl = null;
  1009. let mainFormattedNameUrl = null;
  1010. let mainChannelText = null;
  1011. let mainFormattedNameText = null;
  1012.  
  1013. try {
  1014. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1015. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  1016. mainChannelText = channelNameDOMData.channelName.runs[0].text
  1017. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  1018. } catch (e) { }
  1019.  
  1020. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  1021.  
  1022. let m = /^\/(@[-_a-zA-Z0-9.]{3,30})$/.test(mainChannelUrl);
  1023.  
  1024. if (m && m[1] && mainChannelText !== m[1]) {
  1025.  
  1026. let channelId = obtainChannelId(mainChannelUrl);
  1027. if (channelId) {
  1028. if (mainChannelText.startsWith('@')) return;
  1029. if (mainChannelText.trim() !== mainChannelText) return;
  1030.  
  1031. displayNameResStore.set(channelId, {
  1032. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  1033. externalId: `${channelId}`,
  1034. ownerUrls: [],
  1035. title: mainChannelText,
  1036. vanityChannelUrl: null,
  1037. verified123: true
  1038. });
  1039. }
  1040.  
  1041. }
  1042. }
  1043. }
  1044.  
  1045.  
  1046.  
  1047.  
  1048. };
  1049.  
  1050. // let newAnchorAdded = false;
  1051. /*
  1052.  
  1053. const intersectionobserver = new IntersectionObserver((entries) => {
  1054. let anchorAppear = false;
  1055. for (const entry of entries) {
  1056. if (entry.isIntersecting === true) {
  1057. anchorAppear = true;
  1058. break;
  1059. }
  1060. }
  1061. if (anchorAppear && newAnchorAdded) {
  1062. newAnchorAdded = false; // stacking will be only reset when one or more anchor added to DOM.
  1063. mutex.nextIndex = 0; // higher pirority for new elements being shown
  1064. }
  1065. }, {
  1066. rootMargin:"0px 0px 0px 0px",
  1067. threshold:1
  1068. })
  1069. */
  1070.  
  1071.  
  1072. /* globals WeakRef:false */
  1073.  
  1074. /** @type {(o: Object | null) => WeakRef | null} */
  1075. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  1076.  
  1077. /** @type {(wr: Object | null) => Object | null} */
  1078. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  1079.  
  1080. let lastNewAnchorLastWR = null;
  1081.  
  1082. let domCheckTimeStamp = 0;
  1083.  
  1084. const mutexForDOMMutations = new Mutex();
  1085. const domCheckSelector = isMobile ? 'a[aria-label^="@"][href*="channel/"]' : 'a[id][href*="channel/"]:not([jkrgy])';
  1086.  
  1087. const domChecker = () => {
  1088.  
  1089. const newAnchors = document.querySelectorAll(domCheckSelector);
  1090. if (newAnchors.length === 0) {
  1091. return;
  1092. }
  1093.  
  1094. mutexForDOMMutations.lockWith(lockResolve => {
  1095.  
  1096. const newAnchors = document.querySelectorAll(domCheckSelector);
  1097. if (newAnchors.length === 0) {
  1098. lockResolve();
  1099. return;
  1100. }
  1101.  
  1102. const cNewAnchorFirst = newAnchors[0]; // non-null
  1103. const cNewAnchorLast = newAnchors[newAnchors.length - 1]; // non-null
  1104. /** @type {HTMLElement | null} */
  1105. const lastNewAnchorLast = kRef(lastNewAnchorLastWR); // HTMLElement | null
  1106. lastNewAnchorLastWR = mWeakRef(cNewAnchorLast);
  1107.  
  1108. const ltDOMCheck = domCheckTimeStamp;
  1109. const ctDOMCheck = Date.now();
  1110. domCheckTimeStamp = ctDOMCheck;
  1111.  
  1112. if (!firstDOMCheck) {
  1113. firstDOMCheck = true;
  1114. firstDOMChecker();
  1115. }
  1116.  
  1117. new Promise(resolve => {
  1118. if (lastNewAnchorLast && mutex.nextIndex >= 1) {
  1119.  
  1120. if (ctDOMCheck - ltDOMCheck < 230) {
  1121.  
  1122. } else {
  1123. if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 2) {
  1124. mutex.nextIndex = 0;
  1125. }
  1126. }
  1127.  
  1128. /*
  1129. if (mutex.nextIndex === 0) {
  1130. // no change
  1131. } else if ((lastNewAnchorLast.compareDocumentPosition(cNewAnchorLast) & 2) === 2) { // when "XX replies" clicked
  1132. mutex.nextIndex = 0; // highest priority
  1133. } else if (cNewAnchorLast !== cNewAnchorFirst && (lastNewAnchorLast.compareDocumentPosition(cNewAnchorFirst) & 2) === 1) { // rarely
  1134. mutex.nextIndex = Math.floor(mutex.nextIndex / 2); // relatively higher priority
  1135. }
  1136. */
  1137. }
  1138. resolve();
  1139. }).then(() => {
  1140.  
  1141. // newAnchorAdded = true;
  1142. for (const anchor of newAnchors) {
  1143. // author-text or name
  1144. // normal url: /channel/xxxxxxx
  1145. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  1146. const href = anchor.getAttribute('href');
  1147. const channelId = obtainChannelId(href); // string, can be empty
  1148. anchor.setAttribute('jkrgy', channelId);
  1149. // intersectionobserver.unobserve(anchor);
  1150. // intersectionobserver.observe(anchor); // force first occurance
  1151. domCheck(anchor, href, channelId);
  1152. }
  1153.  
  1154. }).then(lockResolve).catch(e => {
  1155. lockResolve();
  1156. console.warn(e);
  1157. });
  1158.  
  1159. });
  1160.  
  1161.  
  1162. };
  1163.  
  1164.  
  1165. /** @type {MutationObserver | null} */
  1166. let domObserver = null;
  1167.  
  1168. const onPageFetched = isMobile ? (callback, final) => {
  1169.  
  1170. let state = 0;
  1171.  
  1172. window.addEventListener('state-change', function (evt) {
  1173. if (state === 1) return; // ignore intermediate events
  1174. state = 1; // before value: 0 or 2;
  1175. callback(evt);
  1176. }, false);
  1177.  
  1178. window.addEventListener('state-navigateend', function (evt) { // fallback
  1179. let inSeq = state === 1;
  1180. state = 2; // 2 when loaded
  1181. if (!inSeq) callback(evt);
  1182. }, false);
  1183.  
  1184. } : (callback) => {
  1185.  
  1186. let state = 0;
  1187.  
  1188. document.addEventListener('yt-page-data-fetched', function (evt) {
  1189. if (state === 1) return; // ignore intermediate events if any
  1190. state = 1; // before value: 0 or 2;
  1191. callback(evt);
  1192. }, false);
  1193.  
  1194. document.addEventListener('yt-navigate-finish', function (evt) { // fallback
  1195. let inSeq = state === 1;
  1196. state = 2; // 2 when loaded
  1197. if (!inSeq) callback(evt);
  1198. }, false);
  1199.  
  1200. };
  1201.  
  1202. /**
  1203. *
  1204. * @param {Node} app
  1205. * @returns
  1206. */
  1207. function setupOnPageFetched(app) {
  1208.  
  1209. firstDOMCheck = false;
  1210.  
  1211. if (!cfg['INNERTUBE_API_KEY']) {
  1212. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  1213. return;
  1214. }
  1215.  
  1216. if (!domObserver) {
  1217. domObserver = new MutationObserver(domChecker);
  1218. } else {
  1219. domObserver.takeRecords();
  1220. domObserver.disconnect();
  1221. }
  1222.  
  1223. domObserver.observe(app, { childList: true, subtree: true });
  1224. domChecker();
  1225.  
  1226. }
  1227.  
  1228. if (isMobile) {
  1229.  
  1230. onPageFetched(async (evt) => {
  1231. let app = document.querySelector('ytm-app#app') || document.querySelector('ytm-app');
  1232. console.assert(app);
  1233. const ytcfg = ((window || 0).ytcfg || 0);
  1234. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  1235. cfg[key] = ytcfg.get(key);
  1236. }
  1237. setupOnPageFetched(app);
  1238. });
  1239.  
  1240. } else {
  1241.  
  1242. onPageFetched(async (evt) => {
  1243. const app = (evt || 0).target || document.querySelector('ytd-app');
  1244. console.assert(app);
  1245. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  1246. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  1247. cfg[key] = cfgData[key];
  1248. }
  1249. setupOnPageFetched(app);
  1250. });
  1251.  
  1252. }
  1253.  
  1254. })({ Promise, fetch });