YouTube: Add Channel Name to Shorts Thumbnail

在 YouTube Shorts 缩略图中添加频道名称

  1. // ==UserScript==
  2. // @name YouTube: Add Channel Name to Shorts Thumbnail
  3. // @namespace UserScript
  4. // @match https://www.youtube.com/*
  5. // @version 0.2.7
  6. // @license MIT License
  7. // @author CY Fung
  8. // @grant none
  9. // @unwrap
  10. // @inject-into page
  11. // @run-at document-start
  12. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@5d83d154956057bdde19e24f95b332cb9a78fcda/library/default-trusted-type-policy.js
  13. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@8fac46500c5a916e6ed21149f6c25f8d1c56a6a3/library/ytZara.js
  14. // @description To add channel name to YouTube Shorts thumbnail
  15. // @description:ja YouTube Shortsのサムネイルにチャンネル名を追加する
  16. // @description:zh-TW 在 YouTube Shorts 縮圖中添加頻道名稱
  17. // @description:zh-CN 在 YouTube Shorts 缩略图中添加频道名称
  18. // ==/UserScript==
  19.  
  20. /*
  21.  
  22. MIT License
  23.  
  24. Copyright 2024 CY Fung
  25.  
  26. Permission is hereby granted, free of charge, to any person obtaining a copy
  27. of this software and associated documentation files (the "Software"), to deal
  28. in the Software without restriction, including without limitation the rights
  29. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  30. copies of the Software, and to permit persons to whom the Software is
  31. furnished to do so, subject to the following conditions:
  32.  
  33. The above copyright notice and this permission notice shall be included in all
  34. copies or substantial portions of the Software.
  35.  
  36. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  42. SOFTWARE.
  43.  
  44. */
  45.  
  46.  
  47.  
  48. (() => {
  49.  
  50.  
  51. const defaultPolicy = (typeof trustedTypes !== 'undefined' && trustedTypes.defaultPolicy) || { createHTML: s => s };
  52. function createHTML(s) {
  53. return defaultPolicy.createHTML(s);
  54. }
  55.  
  56. let trustHTMLErr = null;
  57. try {
  58. document.createElement('div').innerHTML = createHTML('1');
  59. } catch (e) {
  60. trustHTMLErr = e;
  61. }
  62.  
  63. if (trustHTMLErr) {
  64. console.log(`trustHTMLErr`, trustHTMLErr);
  65. trustHTMLErr(); // exit userscript
  66. }
  67.  
  68.  
  69. // -----------------------------------------------------------------------------------------------------------------------------
  70.  
  71.  
  72.  
  73.  
  74. /** @type {globalThis.PromiseConstructor} */
  75. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  76.  
  77. const fetch_ = fetch;
  78.  
  79. const HTMLElement_ = HTMLElement;
  80.  
  81. /**
  82. * @param {Element} elm
  83. * @param {string} selector
  84. * @returns {Element | null}
  85. * */
  86. const qsOne = (elm, selector) => {
  87. return HTMLElement_.prototype.querySelector.call(elm, selector);
  88. }
  89.  
  90. /**
  91. * @param {Element} elm
  92. * @param {string} selector
  93. * @returns {NodeListOf<Element>}
  94. * */
  95. const qsAll = (elm, selector) => {
  96. return HTMLElement_.prototype.querySelectorAll.call(elm, selector);
  97. }
  98.  
  99. const cssFn = () => `
  100.  
  101. [ePCWu]::before {
  102. width: 100%;
  103. content: attr(ePCWu);
  104. display: block;
  105. max-width: 100%;
  106. text-overflow: ellipsis;
  107. overflow: hidden;
  108. white-space: nowrap;
  109. }
  110. `;
  111.  
  112.  
  113. const addCSSProcess = () => {
  114. if (document.querySelector('style#ePCWv')) return;
  115. const style = document.createElement('style')
  116. style.id = 'ePCWv'
  117. style.textContent = cssFn();
  118. document.head.appendChild(style);
  119. };
  120.  
  121. const { networkRequestOfChannelName } = (() => {
  122.  
  123. let chainPromise = Promise.resolve();
  124.  
  125. const resolvedValues = new Map();
  126.  
  127. /**
  128. *
  129. * @param {Response} fetchRes
  130. * @param {(value: any)=>void} resolve
  131. */
  132. const onFetched = async (fetchRes, resolve) => {
  133. const resText = await fetchRes.text();
  134. let resultName = '';
  135. let wIdx2 = resText.indexOf('itemprop="author"');
  136. let wIdx1 = wIdx2 > 0 ? resText.lastIndexOf('<span', wIdx2) : -1;
  137. let wIdx3 = wIdx1 > 0 ? resText.indexOf('<\/span>', wIdx2) : -1;
  138. if (wIdx3 > 0) {
  139. let mText = resText.substring(wIdx1, wIdx3 + '<\/span>'.length);
  140. let template = document.createElement('template');
  141. template.innerHTML = createHTML(mText);
  142. let span = template.content.firstElementChild;
  143. if (span && span.nodeName === "SPAN") {
  144. const nameElm = qsOne(span, 'link[itemprop="name"]')
  145. resultName = (nameElm ? nameElm.getAttribute('content') : '') || '';
  146. }
  147. template.innerHTML = createHTML('');
  148. }
  149. resolve(resultName);
  150. }
  151.  
  152. const createPromise = (videoId) => {
  153.  
  154. return new Promise(resolve => {
  155.  
  156. chainPromise = chainPromise.then(async () => {
  157.  
  158. let fetchRes = null;
  159. try {
  160.  
  161. fetchRes = await fetch_(`/watch?v=${videoId}`, {
  162.  
  163. "method": "GET",
  164. "mode": "same-origin",
  165. "credentials": "omit",
  166. referrerPolicy: "no-referrer",
  167. cache: "default",
  168. redirect: "error", // there shall be no redirection in this API request
  169. integrity: "",
  170. keepalive: false,
  171.  
  172. "headers": {
  173. "Cache-Control": "public, max-age=900, stale-while-revalidate=1800",
  174. // refer "Cache-Control Use Case Examples" in https://www.koyeb.com/blog/using-cache-control-and-cdns-to-improve-performance-and-reduce-latency
  175. // seems YouTube RSS Feeds server insists its own Cache-Control.
  176.  
  177. // "Content-Type": "text/xml; charset=UTF-8",
  178. "Accept-Encoding": "gzip, deflate, br", // YouTube Response - gzip
  179. // X-Youtube-Bootstrap-Logged-In: false,
  180. // X-Youtube-Client-Name: 1, // INNERTUBE_CONTEXT_CLIENT_NAME
  181. // X-Youtube-Client-Version: "2.20230622.06.00" // INNERTUBE_CONTEXT_CLIENT_VERSION
  182.  
  183. "Accept": "text/html",
  184. "Pragma": ""
  185. }
  186.  
  187. });
  188.  
  189. } catch (e) {
  190. console.warn(e);
  191. }
  192.  
  193. fetchRes && onFetched(fetchRes, resolve).catch(console.warn);
  194.  
  195. });
  196.  
  197.  
  198. });
  199.  
  200.  
  201. };
  202.  
  203. const networkRequestOfChannelName = (videoId) => {
  204. let promise = resolvedValues.get(videoId);
  205. if (!promise) {
  206. promise = createPromise(videoId);
  207. resolvedValues.set(videoId, promise);
  208. }
  209. return promise;
  210. }
  211.  
  212. return { networkRequestOfChannelName };
  213.  
  214. })();
  215.  
  216.  
  217.  
  218. const firstObjectKey = (obj) => {
  219. for (const key in obj) {
  220. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  221. }
  222. return null;
  223. }
  224.  
  225. const getEntryVideoId = (wtObj) => {
  226.  
  227. let videoId = '';
  228.  
  229. if (wtObj.overlayMetadata && typeof wtObj.entityId == 'string' && (wtObj.inlinePlayerData || 0).onVisible) {
  230. const watchEndpoint = ((wtObj.inlinePlayerData || 0).onVisible.innertubeCommand || 0).watchEndpoint || 0;
  231. if (watchEndpoint && typeof (watchEndpoint.videoId || 0) === 'string') {
  232. videoId = watchEndpoint.videoId;
  233. }
  234. }
  235.  
  236. if (!videoId && wtObj.overlayMetadata && typeof wtObj.entityId == 'string' && (wtObj.onTap || 0).innertubeCommand) {
  237. const reelWatchEndpoint = ((wtObj.onTap || 0).innertubeCommand || 0).reelWatchEndpoint || 0;
  238. if (reelWatchEndpoint && typeof (reelWatchEndpoint.videoId || 0) === 'string') {
  239. videoId = reelWatchEndpoint.videoId;
  240. }
  241. }
  242.  
  243. return videoId;
  244. }
  245.  
  246. const getSubheadElement = (mainElement) => {
  247. return qsOne(mainElement, '.ShortsLockupViewModelHostMetadataSubhead, .ShortsLockupViewModelHostOutsideMetadataSubhead, .shortsLockupViewModelHostMetadataSubhead, .shortsLockupViewModelHostOutsideMetadataSubhead');
  248. }
  249.  
  250. const addChannelNamePerItem = async (entry) => {
  251. const wKey = firstObjectKey(entry);
  252. const wObj = wKey ? entry[wKey] : null;
  253. if (wObj) {
  254. const rsVideoId = wObj.rsVideoId;
  255. const videoId = getEntryVideoId(wObj);
  256. if (videoId === rsVideoId && videoId) {
  257. return {
  258. entry,
  259. rsVideoId,
  260. rsChannelName: wObj.rsChannelName
  261. };
  262. } else if (videoId !== rsVideoId && videoId) {
  263. const name = await networkRequestOfChannelName(videoId);
  264. return {
  265. entry,
  266. rsVideoId: videoId,
  267. rsChannelName: name
  268. };
  269. }
  270. }
  271. return {
  272. entry,
  273. rsVideoId: '',
  274. rsChannelName: ''
  275. };
  276. };
  277.  
  278. const apGridListFn = async function (cnt_) {
  279.  
  280. const cnt = cnt_ || this;
  281. // const hostElement = cnt.hostElement || cnt;
  282. const data = cnt.data;
  283.  
  284. const items = data.items;
  285. if (!items || !items.length) return;
  286.  
  287. const itemsElm = (cnt.$ || 0).items || 0;
  288. if (!itemsElm) return;
  289.  
  290. const results = await Promise.all(items.map(addChannelNamePerItem));
  291.  
  292. const mapping = new Map();
  293.  
  294. for (const result of results) {
  295. if (!result || !result.rsVideoId) continue;
  296. const entry = (result.entry || 0);
  297. if (!entry) continue;
  298. const wKey = firstObjectKey(entry);
  299. const wObj = wKey ? entry[wKey] : null;
  300. const entityId = wObj ? wObj.entityId : null;
  301. if (typeof entityId === 'string') {
  302. mapping.set(entityId, result);
  303. }
  304. }
  305.  
  306. for (const elm of qsAll(itemsElm, 'ytm-shorts-lockup-view-model')) {
  307. const entityId = ((elm.data || 0).entityId || 0);
  308.  
  309. let nameToAdd = '';
  310. if (typeof entityId === 'string') {
  311. const result = mapping.get(entityId);
  312. if (result) {
  313. elm.data.rsVideoId = result.rsVideoId;
  314. elm.data.rsChannelName = result.rsChannelName;
  315. nameToAdd = result.rsChannelName;
  316. }
  317. }
  318.  
  319. const subhead = getSubheadElement(elm);
  320. if (subhead) {
  321. if (nameToAdd) {
  322. subhead.setAttribute('ePCWu', nameToAdd);
  323. } else {
  324. subhead.removeAttribute('ePCWu');
  325. }
  326. } else {
  327. console.log('subhead cannot be found', elm);
  328. }
  329.  
  330. }
  331.  
  332. mapping.clear();
  333.  
  334.  
  335. }
  336.  
  337. const apSingleGridFn = async function (cnt_) {
  338.  
  339. let useOldModel = true;
  340. const cnt = cnt_ || this;
  341. const hostElement = cnt.hostElement || cnt;
  342. let nameToAdd = '';
  343. const data = cnt.data;
  344.  
  345. const details = data && data.videoType && data.videoId ? ((cnt.$ || 0).details || 0) : null;
  346. const content = data && data.videoType && data.videoId ? null : ((cnt.$ || 0).content || 0);
  347.  
  348. if (data && data.videoType === "REEL_VIDEO_TYPE_VIDEO" && typeof data.videoId === 'string') {
  349. const videoId = data.videoId;
  350. if (data.rsVideoId === videoId && typeof data.rsChannelName === 'string') {
  351. nameToAdd = data.rsChannelName;
  352.  
  353. const metaline = details ? qsOne(details, '#details #metadata-line') : qsOne(hostElement, 'ytd-reel-item-renderer #details #metadata-line');
  354. if (metaline) {
  355. metaline.setAttribute('ePCWu', nameToAdd);
  356. } else {
  357. console.log('metaline cannot be found', content);
  358. }
  359.  
  360. } else {
  361. const name = await networkRequestOfChannelName(videoId);
  362. cnt.data = Object.assign({}, cnt.data, { rsVideoId: videoId, rsChannelName: name });
  363. }
  364.  
  365. } else if (data && data.content && content instanceof Element) {
  366.  
  367. useOldModel = false;
  368. const wKey = firstObjectKey(data.content);
  369. const wObj = wKey ? data.content[wKey] : null;
  370.  
  371. if (wObj) {
  372.  
  373. const rsVideoId = wObj.rsVideoId;
  374. const videoId = getEntryVideoId(wObj);
  375.  
  376. if (videoId !== rsVideoId && videoId) {
  377. const name = await networkRequestOfChannelName(videoId);
  378. const newFirstObject = Object.assign({}, cnt.data.content[wKey], { rsVideoId: videoId, rsChannelName: name });
  379. const newContent = Object.assign({}, cnt.data.content, { [wKey]: newFirstObject });
  380. cnt.data = Object.assign({}, cnt.data, { content: newContent });
  381. } else if (rsVideoId === videoId && rsVideoId) {
  382. nameToAdd = wObj.rsChannelName;
  383. const subhead = getSubheadElement(content);
  384. if (subhead) {
  385. subhead.setAttribute('ePCWu', nameToAdd);
  386. } else {
  387. console.log('subhead cannot be found', content);
  388. }
  389. }
  390.  
  391. }
  392.  
  393. }
  394.  
  395. if (!nameToAdd) {
  396. if (useOldModel) {
  397. const metaline = details ? qsOne(details, '[ePCWu]') : qsOne(hostElement, '[ePCWu]');
  398. if (metaline) {
  399. metaline.removeAttribute('ePCWu');
  400. }
  401. } else if (content) {
  402. const subhead = qsOne(content, '[ePCWu]');
  403. if (subhead) {
  404. subhead.removeAttribute('ePCWu');
  405. }
  406. }
  407. }
  408.  
  409. };
  410.  
  411. ytZara.ytProtoAsync("ytd-rich-grid-slim-media").then((cProto) => {
  412. Promise.resolve().then(addCSSProcess);
  413. if (cProto && !cProto.__ulLSbep46I6H__ && typeof cProto.onDataChanged === 'function') {
  414. cProto.__ulLSbep46I6H__ = apSingleGridFn;
  415. const onDataChanged = cProto.onDataChanged;
  416. cProto.onDataChanged = function () {
  417. const cnt = this;
  418. Promise.resolve(this).then(apSingleGridFn).catch(console.warn);
  419. return onDataChanged ? onDataChanged.apply(cnt, arguments) : void 0;
  420. };
  421. }
  422. });
  423.  
  424.  
  425. const onVisiblePn = (cProto) => {
  426. Promise.resolve().then(addCSSProcess);
  427. if (cProto && !cProto.__ulLSbep46I6H__ && typeof cProto.onVisible === 'function') {
  428. cProto.__ulLSbep46I6H__ = apSingleGridFn;
  429. const onVisible = cProto.onVisible;
  430. cProto.onVisible = function () {
  431. const cnt = this;
  432. Promise.resolve(this).then(apSingleGridFn).catch(console.warn);
  433. return onVisible ? onVisible.apply(cnt, arguments) : void 0;
  434. };
  435. }
  436. };
  437.  
  438. ytZara.ytProtoAsync("ytd-reel-item-renderer").then(onVisiblePn);
  439. ytZara.ytProtoAsync("ytd-rich-item-renderer").then(onVisiblePn);
  440.  
  441. ytZara.ytProtoAsync("yt-horizontal-list-renderer").then((cProto) => {
  442. Promise.resolve().then(addCSSProcess);
  443. if (cProto && !cProto.__wwVgbwDkvCQY__ && typeof cProto.onVisible === 'function') {
  444. cProto.__wwVgbwDkvCQY__ = apGridListFn;
  445. const onVisible = cProto.onVisible;
  446. cProto.onVisible = function () {
  447. const cnt = this;
  448. Promise.resolve(this).then(apGridListFn).catch(console.warn);
  449. return onVisible ? onVisible.apply(cnt, arguments) : void 0;
  450. };
  451. }
  452. });
  453.  
  454.  
  455. })();

QingJ © 2025

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