Greasy Fork 还支持 简体中文。

Restore YouTube Username from Handle to Custom

To restore YouTube Username to the traditional custom name

目前為 2023-06-15 提交的版本,檢視 最新版本

  1. /*
  2. MIT License
  3. Copyright 2023 CY Fung
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. // ==UserScript==
  21. // @name Restore YouTube Username from Handle to Custom
  22. // @namespace http://tampermonkey.net/
  23. // @version 0.1.1
  24. // @license MIT License
  25. // @description To restore YouTube Username to the traditional custom name
  26.  
  27. // @author CY Fung
  28. // @match https://www.youtube.com/*
  29. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  30. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/general-icon.png
  31. // @supportURL https://github.com/cyfung1031/userscript-supports
  32. // @run-at document-start
  33. // @grant none
  34. // @unwrap
  35. // @allFrames
  36. // @inject-into page
  37. // ==/UserScript==
  38.  
  39. /* jshint esversion:8 */
  40.  
  41. (function () {
  42. 'use strict';
  43.  
  44. const cfg = {};
  45. class Mutex {
  46.  
  47. constructor() {
  48. this.p = Promise.resolve()
  49. }
  50.  
  51. lockWith(f) {
  52.  
  53. this.p = this.p.then(() => new Promise(f)).catch(console.warn)
  54. }
  55.  
  56. }
  57. const mutex = new Mutex();
  58.  
  59. function getDisplayName(channelId) {
  60.  
  61. return new Promise(resolve => {
  62.  
  63.  
  64. mutex.lockWith(lockResolve => {
  65.  
  66.  
  67.  
  68. //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY
  69.  
  70.  
  71. fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
  72. "method": "POST",
  73. "mode": "same-origin",
  74. "credentials": "same-origin",
  75.  
  76. // (-- reference: https://ja.javascript.info/fetch-api
  77. referrerPolicy: "no-referrer",
  78. cache: "default",
  79. redirect: "error",
  80. integrity: "",
  81. keepalive: false,
  82. signal: undefined,
  83. window: window,
  84. // --)
  85.  
  86. "headers": {
  87. "Content-Type": "application/json"
  88. },
  89. "body": JSON.stringify({
  90. "context": {
  91. "client": {
  92. "clientName": "MWEB",
  93. "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
  94. "originalUrl": `https://m.youtube.com/channel/${channelId}`,
  95. "playerType": "UNIPLAYER",
  96. "platform": "MOBILE",
  97. "clientFormFactor": "SMALL_FORM_FACTOR",
  98. "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",
  99. "mainAppWebInfo": {
  100. "graftUrl": `/channel/${channelId}`,
  101. "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
  102. "isWebNativeShareAvailable": true
  103. }
  104. },
  105. "user": {
  106. "lockedSafetyMode": false
  107. },
  108. "request": {
  109. "useSsl": true,
  110. "internalExperimentFlags": [],
  111. "consistencyTokenJars": []
  112. }
  113. },
  114. "browseId": `${channelId}`
  115. })
  116. })).then(res => {
  117. lockResolve();
  118. return res.json();
  119. }).then(res => {
  120.  
  121. let { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;
  122.  
  123.  
  124. resolve({ title, externalId, ownerUrls, channelUrl, vanityChannelUrl });
  125.  
  126. })
  127.  
  128.  
  129.  
  130. });
  131.  
  132.  
  133. });
  134. }
  135.  
  136. const dataChangedFuncStore = new WeakMap();
  137.  
  138.  
  139. const dataChangeFuncProducer = (dataChanged) => {
  140.  
  141. return function () {
  142. let p = this.querySelector('#author-text[href^="/channel/"]');
  143. if (p && (this.data || 0).jkrgx !== 1) p.classList.remove('jkrgx');
  144. return dataChanged.apply(this, arguments)
  145. }
  146.  
  147.  
  148. }
  149.  
  150. const domCheck = async (anchor) => {
  151.  
  152.  
  153. let channelHref = anchor.getAttribute('href');
  154. if (!channelHref) return;
  155. let parentNode = anchor.parentNode;
  156. while (parentNode instanceof Node) {
  157. if (typeof parentNode.is === 'string') break;
  158. parentNode = parentNode.parentNode
  159. }
  160. if (parentNode instanceof Node && typeof parentNode.is === 'string') { } else return;
  161. let authorText = (parentNode.data || 0).authorText;
  162. if (authorText && typeof authorText.simpleText === 'string') { } else return;
  163. const currentDisplayed = authorText.simpleText;
  164. if (!/\s*\@[a-zA-Z0-9_\-]+\s*/.test(currentDisplayed)) return;
  165.  
  166. let m = /\/channel\/([^\/\?\#]+)/.exec(channelHref);
  167. if (!m || !m[1]) return;
  168.  
  169. let oldDataChanged = parentNode.dataChanged;
  170. if (typeof oldDataChanged === 'function' && !oldDataChanged.jkrgx) {
  171. let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
  172. if (!newDataChanged) {
  173. newDataChanged = dataChangeFuncProducer(oldDataChanged);
  174. newDataChanged.jkrgx = 1;
  175. dataChangedFuncStore.set(oldDataChanged, newDataChanged);
  176. }
  177. parentNode.dataChanged = newDataChanged;
  178. }
  179.  
  180. const fetchResult = await getDisplayName(m[1]);
  181.  
  182.  
  183. const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;
  184.  
  185. if (anchor.getAttribute('href') !== `/channel/${externalId}`) return;
  186. if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNode.data === 'object') {
  187.  
  188.  
  189. if (authorText.simpleText !== currentDisplayed) return;
  190. let currentDisplayTrimmed = currentDisplayed.trim();
  191. let match = false;
  192. for (const ownerUrl of ownerUrls) {
  193.  
  194. if (ownerUrl.endsWith(`/${currentDisplayTrimmed}`)) {
  195. match = true;
  196. break;
  197. }
  198. }
  199. if (match && currentDisplayed !== title) {
  200. authorText.simpleText = title;
  201. parentNode.data = Object.assign({}, parentNode.data, { jkrgx: 1 });
  202. }
  203.  
  204. }
  205.  
  206.  
  207. }
  208.  
  209. const domChecker = () => {
  210.  
  211. for (const anchor of document.querySelectorAll('#author-text[href^="/channel/"]:not(.jkrgx)')) {
  212. anchor.classList.add('jkrgx');
  213.  
  214. domCheck(anchor);
  215. }
  216.  
  217. };
  218.  
  219.  
  220. /** @type {MutationObserver | null} */
  221. let domObserver = null;
  222.  
  223. document.addEventListener('yt-page-data-fetched', function () {
  224.  
  225. try {
  226. for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
  227. cfg[key] = window.ytcfg.data_[key];
  228. }
  229. } catch (e) { }
  230.  
  231. if (!cfg['INNERTUBE_API_KEY']) return;
  232.  
  233. if (!domObserver) {
  234. domObserver = new MutationObserver((mutationList) => {
  235. domChecker();
  236. });
  237. } else {
  238. domObserver.takeRecords();
  239. domObserver.disconnect();
  240. }
  241.  
  242. domObserver.observe(document.body, { childList: true, subtree: true });
  243. domChecker();
  244.  
  245. });
  246.  
  247.  
  248. })();