Restore YouTube Username from Handle to Custom

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

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

  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.3.4
  30. // @license MIT License
  31.  
  32. // @author CY Fung
  33. // @match https://www.youtube.com/*
  34. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  35. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/general-icon.png
  36. // @supportURL https://github.com/cyfung1031/userscript-supports
  37. // @run-at document-start
  38. // @grant none
  39. // @unwrap
  40. // @allFrames
  41. // @inject-into page
  42.  
  43. // @description To restore YouTube Username to the traditional custom name
  44. // @description:ja YouTubeのユーザー名を伝統的なカスタム名に復元するために。
  45. // @description:zh-TW 將 YouTube 使用者名稱從 Handle 恢復為自訂名稱
  46. // @description:zh-CN 将 YouTube 用户名从 Handle 恢复为自定义名称
  47. // @description:ko YouTube 사용자 이름을 전통적인 사용자 지정 이름으로 복원합니다.
  48. // @description:ru Восстановление имени пользователя YouTube с помощью обычного настраиваемого имени
  49. // @description:af Herstel YouTube-gebruikersnaam vanaf Handvat na Aangepaste Naam
  50. // @description:az YouTube İstifadəçi Adını Özəl Adından İstifadə Etmək
  51. // @description:id Mengembalikan Nama Pengguna YouTube dari Handle ke Kustom
  52. // @description:ms Pulihkan Nama Pengguna YouTube dari Handle ke Tersuai
  53. // @description:bs Vrati YouTube korisničko ime sa ručke na prilagođeno ime
  54. // @description:ca Restaurar el nom d'usuari de YouTube de la màniga al personalitzat
  55. // @description:cs Obnovte uživatelské jméno YouTube z rukojeti na vlastní
  56. // @description:da Gendan YouTube-brugernavn fra Håndtag til Brugerdefineret
  57. // @description:de Stellt den YouTube-Benutzernamen von Handle auf Benutzerdefiniert wieder her
  58. // @description:et Taasta YouTube'i kasutajanimi käepidemelt kohandatud nimeks
  59. // @description:es Restaurar el nombre de usuario de YouTube de la manija al personalizado
  60. // @description:eu Berrezarri YouTube Erabiltzaile-izena Manipulatik Pertsonalizatuera
  61. // @description:fr Restaurer le nom d'utilisateur YouTube de la poignée au nom personnalisé
  62. // @description:gl Restaura o nome de usuario de YouTube da manexa ao personalizado
  63. // @description:hr Vrati YouTube korisničko ime s ručke na prilagođeno ime
  64. // @description:zu Hlanganisa Igama Lokusebenza lwe-YouTube kusuka kwi-Handle kuze kube kusebenza kakhulu
  65. // @description:is Endurheimtu YouTube Notandanafn frá Handfangi til Sérsniðins
  66. // @description:it Ripristina il nome utente di YouTube da Handle a Personalizzato
  67. // @description:sw Rejesha Jina la Mtumiaji wa YouTube kutoka kwa Kishughulikia hadi Desturi
  68. // @description:lv Atjaunot YouTube lietotāja vārdu no roktura uz pielāgotu
  69. // @description:lt Atkurti „YouTube“ naudotojo vardą iš rankenos į tinkamą
  70. // @description:hu Visszaállítja a YouTube felhasználónevet a fogantyútól a testreszabottra
  71. // @description:nl Herstel YouTube-gebruikersnaam van Handle naar Aangepaste naam
  72. // @description:uz YouTube foydalanuvchining nomini Hurda dan Shaxsiylashtirilgan nomga qaytarish
  73. // @description:pl Przywróć nazwę użytkownika YouTube z uchwytu na niestandardową
  74. // @description:pt Restaurar o nome de usuário do YouTube de Handle para Personalizado
  75. // @description:pt-BR Restaurar o nome de usuário do YouTube de Handle para Personalizado
  76. // @description:ro Restaurați Numele de Utilizator YouTube de la Mâner la Personalizat
  77. // @description:sq Rikthe emrin e përdoruesit të YouTube nga Maja në Personalizuar
  78. // @description:sk Obnovte používateľské meno YouTube z rukoväte na vlastné
  79. // @description:sl Obnovite uporabniško ime YouTube iz ročaja v prilagojeno ime
  80. // @description:sr Вратите YouTube корисничко име са ручке на прилагођено име
  81. // @description:fi Palauta YouTube-käyttäjänimi kahvasta räätälöityyn nimeen
  82. // @description:sv Återställ YouTube-användarnamnet från handtaget till anpassat namn
  83. // @description:vi Khôi phục Tên người dùng YouTube từ Tay cầm thành Tùy chỉnh
  84. // @description:tr Özel İsme Kullanıcı Adını İade Etme
  85. // @description:be Вярнуць імя карыстальніка YouTube з ручкі на наладжваецца
  86. // @description:bg Възстановяване на потребителско име на YouTube от дръжка до персонализирано име
  87. // @description:ky YouTube колдонуучунун атты боюнча атын тамашалау
  88. // @description:kk YouTube пайдаланушының атын Handle танымасынан Жеке атауға қайта түсіру
  89. // @description:mk Врати го името на YouTube корисникот од држачот во прилагодено име
  90. // @description:mn YouTube хэрэглэгчийн нэрийг хүчирхийлэгчидээс Байгууллагад нь солих
  91. // @description:uk Відновлення імені користувача YouTube з ручки на налаштоване ім'я
  92. // @description:el Επαναφορά Ονόματος Χρήστη YouTube από τη Λαβή σε Προσαρμοσμένο
  93. // @description:hy Վերականգնել YouTube-ի Օգտագործողի Անունը Ձեռքից Հատուցվածությանով
  94. // @description:ur ہینڈل سے یوٹیوب یوزر نیم کو کسٹم میں بحال کریں
  95. // @description:ar استعادة اسم مستخدم YouTube من المقبض إلى مخصص
  96. // @description:fa بازیابی نام کاربری یوتیوب از دستگیره به سفارشی
  97. // @description:ne ह्यान्डलबाट यूट्युब प्रयोगकर्तानाम अनुकूलमा उपयोग गर्नुहोस्
  98. // @description:mr हॅंडलमधून यूट्यूब वापरकर्तानाव अनुकूलित करा
  99. // @description:hi हैंडल से यूट्यूब यूजरनेम को कस्टम में बदलें
  100. // @description:as কাস্টম হতে হ্যান্ডেল পৰা ইউটিউব ব্যৱহাৰকাৰী নাম পুনৰ্স্থাপন কৰক
  101. // @description:bn হ্যান্ডেল থেকে কাস্টম করে ইউটিউব ব্যবহারকারীর নাম পুনরুদ্ধার করুন
  102. // @description:pa ਯੂਟਿਊਬ ਯੂਜਰਨਾਂ ਦਾ ਨਾਂ ਹੈਂਡਲ ਤੋਂ ਕਸਟਮ ਵਿੱਚ ਮੁੜ ਲਾਓ
  103. // @description:gu હેન્ડલથી કસ્ટમમાંથી YouTube વપરાશકર્તાનું નામ પુનર્સ્થાપિત કરો
  104. // @description:or କଷ୍ଟମରେ ହେନ୍ଡେଲରୁ YouTube ବ୍ୟବହାରକାରୀଙ୍କ ନାମ ପୁନର୍ପ୍ରାପ୍ତ କରନ୍ତୁ
  105. // @description:ta ஹேண்டில் இருந்து கஸ்டம் ஆக்கும் யூடியூப் பயனர்பெயரை மீட்டமைக்கவும்
  106. // @description:te హాండును నుంచి YouTube వాడుకరి పేరును కస్టమ్‌కు పునరుద్ధరించండి
  107. // @description:kn ಹ್ಯಾಂಡಲ್‌ನಿಂದ YouTube ಬಳಕೆದಾರ ಹೆಸರನ್ನು ಅನುಕೂಲಿತ ಮಾಡಿ
  108. // @description:ml ഹാന്റിൽ നിന്ന് കസ്റ്റം ആക്കാംമെന്ന് യുട്യൂബ് ഉപയോക്തൃനാമം മറ്റുള്ളവരെ മാറ്റുക
  109. // @description:si හැන්ඩල් සහිතව YouTube භාවිතයේ පරිශීලක නාමය ස්වයං කරයි
  110. // @description:th กู้คืนชื่อผู้ใช้ YouTube จากแฮนดิลไปเป็นชื่อที่กำหนดเอง
  111. // @description:lo ເຮັດຊະນິດຊື່ຜູ້ໃຊ້ YouTube ຈາກ Handle ຈົດໄວ້ເປັນຊື່ປັດຈຸບັນ
  112. // @description:my Handle မှ YouTube အသုံးပြုသူအမည်ကို စတင်ပြန်စစ်ဆေးပါ
  113. // @description:ka YouTube მომხმარებლის სახელის აღდგენა ხანდლიდან მორგებულ სახელში
  114. // @description:am ስለ YouTube የተጠቃሚ ስም ማስቀመጫዎቹን ከ Handle ወደ Custom ውስጥ እንደሚመጣ ይረዳሉ
  115. // @description:km កំណត់ YouTube ពាក្យឈ្មោះពី Handle ទៅជាឈ្មោះផ្ទាល់ខ្លួន
  116.  
  117. // ==/UserScript==
  118.  
  119. /* jshint esversion:8 */
  120.  
  121. (function () {
  122. 'use strict';
  123.  
  124. const cfg = {};
  125. class Mutex {
  126.  
  127. constructor() {
  128. this.p = Promise.resolve()
  129. }
  130.  
  131. lockWith(f) {
  132. this.p = this.p.then(() => new Promise(f)).catch(console.warn)
  133. }
  134.  
  135. }
  136. const mutex = new Mutex();
  137.  
  138. const displayNameCacheStore = new Map();
  139.  
  140. const promisesStore = {};
  141.  
  142. function createNetworkPromise(channelId) {
  143.  
  144. return new Promise(networkResolve => {
  145.  
  146.  
  147. mutex.lockWith(lockResolve => {
  148.  
  149. if (!document.querySelector(`[jkrgy="${channelId}"]`)) {
  150. // element has already been removed
  151. lockResolve();
  152. networkResolve(null);
  153. return;
  154. }
  155.  
  156. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  157.  
  158.  
  159. fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  160. "method": "POST",
  161. "mode": "same-origin",
  162. "credentials": "same-origin",
  163.  
  164. // (-- reference: https://javascript.info/fetch-api
  165. referrerPolicy: "no-referrer",
  166. cache: "default",
  167. redirect: "error",
  168. integrity: "",
  169. keepalive: false,
  170. signal: undefined,
  171. window: window,
  172. // --)
  173.  
  174. "headers": {
  175. "Content-Type": "application/json",
  176. "Accept-Encoding": "gzip, deflate, br"
  177. },
  178. "body": JSON.stringify({
  179. "context": {
  180. "client": {
  181. "clientName": "MWEB",
  182. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  183. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  184. "playerType": "UNIPLAYER",
  185. "platform": "MOBILE",
  186. "clientFormFactor": "SMALL_FORM_FACTOR",
  187. "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",
  188. "mainAppWebInfo": {
  189. "graftUrl": `/channel/${channelId}`,
  190. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  191. "isWebNativeShareAvailable": true
  192. }
  193. },
  194. "user": {
  195. "lockedSafetyMode": false
  196. },
  197. "request": {
  198. "useSsl": true,
  199. "internalExperimentFlags": [],
  200. "consistencyTokenJars": []
  201. }
  202. },
  203. "browseId": `${channelId}`
  204. })
  205. })).then(res => {
  206. lockResolve();
  207. return res.json();
  208. }).then(res => {
  209. networkResolve(res);
  210. }).catch(e => {
  211. lockResolve();
  212. console.warn(e);
  213. networkResolve(null);
  214. })
  215.  
  216.  
  217.  
  218. });
  219.  
  220. })
  221.  
  222. }
  223.  
  224. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : requestAnimationFrame;
  225.  
  226. function getDisplayName(channelId) {
  227.  
  228. return new Promise(resolve => {
  229.  
  230. let cachedResult = displayNameCacheStore.get(channelId);
  231. if (cachedResult) {
  232. resolve(cachedResult);
  233. return;
  234. }
  235.  
  236. if (!promisesStore[channelId]) promisesStore[channelId] = createNetworkPromise(channelId);
  237.  
  238. promisesStore[channelId].then(res => {
  239. // res might be null
  240.  
  241. queueMicrotask_(() => {
  242. promisesStore[channelId] = null;
  243. delete promisesStore[channelId];
  244. });
  245.  
  246. let resultInfo = ((res || 0).metadata || 0).channelMetadataRenderer;
  247.  
  248. if (!resultInfo) {
  249. resolve(null);
  250. } else {
  251.  
  252. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;
  253.  
  254. const displayNameRes = { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified: false };
  255. displayNameCacheStore.set(channelId, displayNameRes);
  256.  
  257. resolve(displayNameRes);
  258.  
  259. }
  260.  
  261.  
  262. }).catch(console.warn);
  263.  
  264. }).catch(console.warn);
  265. }
  266.  
  267. const dataChangedFuncStore = new WeakMap();
  268.  
  269. const obtainChannelId = (href) => {
  270. let m = /\/channel\/([^/?#\s]+)/.exec(`/${href}`);
  271. return !m ? '' : (m[1] || '');
  272. };
  273.  
  274. const dataChangeFuncProducer = (dataChanged) => {
  275.  
  276. return function () {
  277. let anchors = null;
  278. try {
  279. anchors = HTMLElement.prototype.querySelectorAll.call(this, 'a[id][href*="channel/"][jkrgy]');
  280. } catch (e) { }
  281. if ((anchors || 0).length >= 1 && (this.data || 0).jkrgx !== 1) {
  282. for (const anchor of anchors) {
  283. anchor.removeAttribute('jkrgy');
  284. }
  285. }
  286. return dataChanged.apply(this, arguments)
  287. }
  288.  
  289.  
  290. };
  291.  
  292. const anchorIntegrityCheck = (anchor, channelHref, channelId) => {
  293.  
  294. // https://www.youtube.com/channel/UCRmLncxsQFcOOC8OhzUIfxQ/videos /channel/UCRmLncxsQFcOOC8OhzUIfxQ UCRmLncxsQFcOOC8OhzUIfxQ
  295.  
  296.  
  297. let currentHref = anchor.getAttribute('href');
  298. if (currentHref === channelHref) return true; // /channel/UCRmLncxsQFcOOC8OhzUIfxQ // /channel/UCRmLncxsQFcOOC8OhzUIfxQ
  299.  
  300. return (currentHref + '/').indexOf(channelHref + '/') >= 0;
  301.  
  302. };
  303.  
  304. const verifyAndConvertHandle = (currentDisplayed, fetchResult) => {
  305.  
  306. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl, verified } = fetchResult;
  307.  
  308. const currentDisplayTrimmed = currentDisplayed.trim();
  309. let match = false;
  310. if (verified) {
  311. match = true;
  312. } else if ((vanityChannelUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  313. match = true;
  314. } else if ((ownerUrls || 0).length >= 1) {
  315. for (const ownerUrl of ownerUrls) {
  316. if ((ownerUrl || '').endsWith(`/${currentDisplayTrimmed}`)) {
  317. match = true;
  318. break;
  319. }
  320. }
  321. }
  322. if (match) {
  323. return currentDisplayTrimmed;
  324. }
  325. return '';
  326.  
  327. };
  328.  
  329. const isDisplayAsHandle = (text) => {
  330.  
  331. if (typeof text !== 'string') return false;
  332. if (text.length < 4) return false;
  333. if (text.indexOf('@') < 0) return false;
  334. return /^\s*@[a-zA-Z0-9_\-.]{3,30}\s*$/.test(text);
  335.  
  336.  
  337. /* https://support.google.com/youtube/answer/11585688?hl=en&co=GENIE.Platform%3DAndroid
  338.  
  339. Handle naming guidelines
  340.  
  341. Is between 3-30 characters
  342. Is made up of alphanumeric characters (A–Z, a–z, 0–9)
  343. Your handle can also include: underscores (_), hyphens (-), dots (.)
  344. Is not URL-like or phone number-like
  345. Is not already being used
  346. Follows YouTube's Community Guidelines
  347.  
  348. // auto handle - without dot (.)
  349.  
  350. */
  351.  
  352. };
  353.  
  354. const contentTextProcess = (contentTexts, idx) => {
  355. const contentText = contentTexts[idx];
  356. const text = (contentText || 0).text;
  357. const url = (((contentText.navigationEndpoint || 0).commandMetadata || 0).webCommandMetadata || 0).url;
  358. if (typeof url === 'string' && typeof text === 'string') {
  359.  
  360. if (!isDisplayAsHandle(text)) return null;
  361. const channelId = obtainChannelId(url);
  362.  
  363. return getDisplayName(channelId).then(fetchResult => {
  364. let resolveResult = null;
  365. if (fetchResult) {
  366. // note: if that user shown is not found in `a[id]`, the hyperlink would not change
  367.  
  368. const textTrimmed = verifyAndConvertHandle(text, fetchResult);
  369. if (textTrimmed) {
  370. resolveResult = (md) => {
  371. let runs = ((md || 0).contentText || 0).runs;
  372. if (!runs || !runs[idx]) return;
  373. if (runs[idx].text !== text) return;
  374. runs[idx].text = text.replace(textTrimmed, `@${fetchResult.title}`); // HyperLink always @SomeOne
  375. md.contentText = Object.assign({}, md.contentText);
  376. };
  377. }
  378. }
  379. return (resolveResult); // function as a Promise
  380. });
  381. }
  382.  
  383. return null;
  384. };
  385.  
  386. const domCheck = async (anchor, channelHref, mt) => {
  387.  
  388. try {
  389. if (!channelHref || !mt) return;
  390. let parentNode = anchor.parentNode;
  391. while (parentNode instanceof Node) {
  392. if (typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') break;
  393. parentNode = parentNode.parentNode
  394. }
  395. if (parentNode instanceof Node && typeof parentNode.is === 'string' && typeof parentNode.dataChanged === 'function') { } else return;
  396. const authorText = (parentNode.data || 0).authorText;
  397. const currentDisplayed = (authorText || 0).simpleText;
  398. if (typeof currentDisplayed !== 'string') return;
  399. if (!isDisplayAsHandle(currentDisplayed)) return;
  400.  
  401. const oldDataChanged = parentNode.dataChanged;
  402. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  403. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  404. if (!newDataChanged) {
  405. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  406. newDataChanged.jkrgx = 1;
  407. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  408. }
  409. parentNode.dataChanged = newDataChanged;
  410. }
  411.  
  412. const fetchResult = await getDisplayName(mt);
  413.  
  414. if (fetchResult === null) return;
  415.  
  416. const { title, externalId } = fetchResult;
  417.  
  418. if (externalId !== mt) return; // channel id must be the same
  419.  
  420. // anchor href might be changed by external
  421. if (!anchorIntegrityCheck(anchor, channelHref, externalId)) return;
  422.  
  423. const parentNodeData = parentNode.data
  424. const funcPromises = [];
  425. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNodeData === 'object' && parentNodeData && parentNodeData.authorText === authorText) {
  426.  
  427. if (authorText.simpleText !== currentDisplayed) return;
  428. const currentDisplayTrimmed = verifyAndConvertHandle(currentDisplayed, fetchResult);
  429. const cSimpleText = ((parentNodeData.authorText || 0).simpleText || '');
  430. if (currentDisplayTrimmed && currentDisplayed !== title && cSimpleText === currentDisplayed) {
  431.  
  432. // the inside hyperlinks will be only converted if its parent author name is handle
  433. const contentTexts = (parentNodeData.contentText || 0).runs;
  434. if (contentTexts && contentTexts.length >= 1) {
  435. for (let aidx = 0; aidx < contentTexts.length; aidx++) {
  436. const r = contentTextProcess(contentTexts, aidx);
  437. if (r instanceof Promise) funcPromises.push(r);
  438. }
  439. }
  440.  
  441. const md = Object.assign({}, parentNodeData);
  442. let setBadge = false;
  443. if (((((md.authorCommentBadge || 0).authorCommentBadgeRenderer || 0).authorText || 0).simpleText || '').trim() === cSimpleText.trim()) {
  444. setBadge = true;
  445. }
  446. // parentNode.data = Object.assign({}, { jkrgx: 1 });
  447. md.authorText = Object.assign({}, md.authorText, { simpleText: currentDisplayed.replace(currentDisplayTrimmed, title) });
  448. if (setBadge) {
  449. md.authorCommentBadge = Object.assign({}, md.authorCommentBadge);
  450. md.authorCommentBadge.authorCommentBadgeRenderer = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer);
  451. md.authorCommentBadge.authorCommentBadgeRenderer.authorText = Object.assign({}, md.authorCommentBadge.authorCommentBadgeRenderer.authorText, { simpleText: title });
  452.  
  453. }
  454. if (funcPromises.length >= 1) {
  455. let funcs = await Promise.all(funcPromises);
  456.  
  457. for (const func of funcs) {
  458. if (typeof func === 'function') {
  459. func(md);
  460. }
  461. }
  462. }
  463. parentNode.data = Object.assign({}, md, { jkrgx: 1 });
  464. }
  465.  
  466. }
  467. } catch (e) {
  468. console.warn(e);
  469. }
  470.  
  471.  
  472. }
  473.  
  474. let firstDOMCheck = false;
  475. const firstDOMChecker = () => {
  476.  
  477. let channelNameDOM = document.querySelector('ytd-channel-name.ytd-video-owner-renderer');
  478. let channelNameDOMData = (channelNameDOM || 0).__data;
  479. if (channelNameDOMData) {
  480. let mainChannelUrl = null;
  481. let mainFormattedNameUrl = null;
  482. let mainChannelText = null;
  483. let mainFormattedNameText = null;
  484.  
  485. try {
  486. mainChannelUrl = channelNameDOMData.channelName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  487. mainFormattedNameUrl = channelNameDOMData.formattedName.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl
  488. mainChannelText = channelNameDOMData.channelName.runs[0].text
  489. mainFormattedNameText = channelNameDOMData.formattedName.runs[0].text
  490. } catch (e) { }
  491.  
  492. if (mainChannelUrl === mainFormattedNameUrl && mainChannelText === mainFormattedNameText && typeof mainChannelUrl === 'string' && typeof mainChannelText === 'string') {
  493.  
  494. let m = /^\/(@[a-zA-Z0-9_\-.]{3,30})$/.test(mainChannelUrl);
  495.  
  496. if (m && m[1] && mainChannelText !== m[1]) {
  497.  
  498. let channelId = obtainChannelId(mainChannelUrl);
  499. if (channelId) {
  500. if (mainChannelText.startsWith('@')) return;
  501. if (mainChannelText.trim() !== mainChannelText) return;
  502.  
  503. displayNameCacheStore.set(channelId, {
  504. channelUrl: `https://www.youtube.com/channel/${channelId}`,
  505. externalId: `${channelId}`,
  506. ownerUrls: [],
  507. title: mainChannelText,
  508. vanityChannelUrl: null,
  509. verified: true
  510. });
  511. }
  512.  
  513. }
  514. }
  515. }
  516.  
  517.  
  518. };
  519.  
  520. const domChecker = () => {
  521.  
  522. const newAnchors = document.querySelectorAll('a[id][href*="channel/"]:not([jkrgy])');
  523. for (const anchor of newAnchors) {
  524. // author-text or name
  525. // normal url: /channel/xxxxxxx
  526. // Improve YouTube! - https://www.youtube.com/channel/xxxxxxx/videos
  527. const href = anchor.getAttribute('href');
  528. const channelId = obtainChannelId(href); // string, can be empty
  529. anchor.setAttribute('jkrgy', channelId);
  530. if (!firstDOMCheck) {
  531. firstDOMCheck = true;
  532. firstDOMChecker();
  533. }
  534. domCheck(anchor, href, channelId);
  535. }
  536.  
  537. };
  538.  
  539.  
  540. /** @type {MutationObserver | null} */
  541. let domObserver = null;
  542.  
  543. document.addEventListener('yt-page-data-fetched', function (evt) {
  544.  
  545. const cfgData = (((window || 0).ytcfg || 0).data_ || 0);
  546. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  547. cfg[key] = cfgData[key];
  548. }
  549.  
  550. if (!cfg['INNERTUBE_API_KEY']) {
  551. console.warn("Userscript Error: INNERTUBE_API_KEY is not found.");
  552. return;
  553. }
  554.  
  555. if (!domObserver) {
  556. domObserver = new MutationObserver(domChecker);
  557. } else {
  558. domObserver.takeRecords();
  559. domObserver.disconnect();
  560. }
  561.  
  562. domObserver.observe(evt.target || document.body, { childList: true, subtree: true });
  563. domChecker();
  564.  
  565. });
  566.  
  567.  
  568. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址