Return YouTube Comment Username

This script replaces the "handle" in the YouTube comments section to user name

  1. // ==UserScript==
  2. // @match https://www.youtube.com/*
  3. // @version 0.6.0
  4. // @run-at document-start
  5. // @name Return YouTube Comment Username
  6. // @name:ja YouTubeコメント欄の名前を元に戻す
  7. // @description This script replaces the "handle" in the YouTube comments section to user name
  8. // @description:ja YouTubeのコメント欄の名前をハンドル(@...)からユーザー名に書き換えます。
  9. // @name:zh-CN 恢復 YouTube 评论用户名
  10. // @name:zh-TW 恢復 YouTube 評論名稱
  11. // @description:zh-TW 此腳本將 YouTube 評論部分中的“handle”替換為用戶名
  12. // @description:zh-CN 此脚本将 YouTube 评论部分中的“handle”替换为用户名
  13. // @author yakisova41
  14. // @namespace https://yt-returnname-api.pages.dev/extension/
  15. // @grant unsafeWindow
  16. // @license MIT
  17. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAWJAAAFiQFtaJ36AAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABI5JREFUaIHVml1ok1cYx39v4pT6Ebdo0baoWCd+VsEPNqfthigOi0IZnRc1XgxFELwQBGE474eIV1UoOqsw9MILSzsv1G4wRQe1zG9RWdGWVBgSMGldrab/XTy2Sc2bj2aZSf5wyMk5zzn5P5/nzUkcSYzAcT4GAsDXwGpgHIWBIaAT+AU4idQ/MiPJGnwpeC5Qgbeg4LNh3vHkXxUAuUzbP4L1knAEfuARMD0/0ZE1eoElHmA3xUceoBz4zgN8k28m/wGbHUEfMCnfTLLE344gCnjyzSRLyEOhkV+2DM6dg5s34exZqKpKLV8AJTHWNm2SBgY0CgMD0saNydYMOQIl1a6iAmpqYOZMCIehsxNu3cqxyd9h3Djo6oJZsxLnnj2DefMgGn1/Ru4eqKyULlyQhoaUgBs3pMWLc2/95csTPyseVVWuHkhUYMUK6cULW9TWJgUCUk2NtGWLdOqUFI1KoZC0cGFuFVi6NLUC7kZ7TwGfT+ruNpINDZLjSAsWSFOmxGR27LANr13LjNj69bZPOjmPR3ryxJ38o0c2n1aBgwdtwZEj0rRpRlIyj1y/bv1AQLp6NZVbR7eWFqm11YyTTnbdOikSGU0+HJbWrk2axKMVuH/f4r6iQjp50jZ48EA6fTq2YXW1dPiw9XftSk+qtdVk79yR5s5NL19ZKR07Jl2+LDU2plszFHveHz8eFi2C7m4IBqG+3sa3b4fbt6GhAbxeePoUXr60uUnvDvCSEvD73atLSYm9VlVBRwds2wbt7cmrUTgM589DeTn09kIkkrp6jWjj95ul7t6VJk6MWdznk5Yssf7goOT1Ss3N9r6uztYGAqkTMB5v3kgHDiRas7zc9nU7B5qbpbIyVw/EzgHHgYEB6OuD0lLTfsYMOHMGVq0y70SjsHcvHD1qsnPmmMWmTnWv3wCzZ8PkySYfDMbG792D16+tv3o1tLRAWVlyS/f2wtatdhbF23+URu3tpvWGDVZtBgft/aVL0r59MauEQlJtbW7KZ2mpFAxm5r2eHmn69BRJXFdngl1dVj79fmn+/Nj8ypVSfb1VqFyQB6mpKfPwk6Tjx5OE0DAaG2HPHnN5W5u5GixcNm+GpiY4dCh1YmUKn89CY9IYnuYjEUvwvj6XEBpuO3dKDx8mav/4sbR7d+6sX109NusPY80alzIajxMnrFVUWHL291sChkI5MfwIvF64cmXs6yZMGO6leRotfLwqrC8zY0ePB7v1KlbcdQRvAW++mWSJWkcwCHyUbyZZ4A/gCw/FmcR/Ad8iqRgVuAh8jtQDdn2eiQIXgf60UrnHZOziLQTcA35Duh8vkMn9/+9Itf8DuZwgXRkVsP8DcckK6XLgZ6SOD0UmGziCCBZr8RBWXhcgPfvwtDJHMg84wJFCJw/mgZeAL25MwAvgU6RwfmhlDrckdoAfioE8mAdCwCdxYw+BZUhv88RpTHDzwP5iIQ+JP278inQxL0yyRHwVGqLADy03xIfQT0h/5pNMNnAEz4EpwHyk5/kmNFYM58CPxUgezAMdwFfE/wOkiOABvi9W8gD/AtVVmDkJXLSNAAAAAElFTkSuQmCC
  18. // ==/UserScript==
  19.  
  20. // src/index.ts
  21. function c3JjL2luZGV4LnRz() {
  22. "use strict";
  23. (() => {
  24. // node_modules/crx-monkey/dist/client/main.js
  25. function getRunningRuntime() {
  26. if (typeof window.__CRX_CONTENT_BUILD_ID === "undefined") {
  27. return "Userscript";
  28. } else {
  29. return "Extension";
  30. }
  31. }
  32. async function bypassSendMessage(message, options, callback) {
  33. const actionId = crypto.randomUUID();
  34. window.postMessage(
  35. {
  36. type: "send-message",
  37. crxContentBuildId: window.__CRX_CONTENT_BUILD_ID,
  38. detail: { message, options },
  39. actionId,
  40. },
  41. "*",
  42. );
  43. const data = await waitResultOnce("send-message", actionId);
  44. if (callback !== void 0) {
  45. callback(data.response);
  46. }
  47. }
  48. async function waitResultOnce(type, actionId) {
  49. return new Promise((resolve) => {
  50. const onResult = (e) => {
  51. if (e.detail.type === type && e.detail.actionId === actionId) {
  52. window.removeEventListener(
  53. "crx-isolate-connector-result",
  54. onResult,
  55. );
  56. resolve(e.detail.data);
  57. }
  58. };
  59. window.addEventListener("crx-isolate-connector-result", onResult);
  60. });
  61. }
  62.  
  63. // src/utils/isCommentRenderer.ts
  64. function isCommentRenderer(continuationItems) {
  65. if (continuationItems.length > 0) {
  66. if ("commentThreadRenderer" in continuationItems[0]) {
  67. return false;
  68. }
  69. if ("commentRenderer" in continuationItems[0]) {
  70. return true;
  71. }
  72. }
  73. return false;
  74. }
  75. function isCommentRendererV2(continuationItems) {
  76. if (continuationItems.length > 0) {
  77. if ("commentThreadRenderer" in continuationItems[0]) {
  78. return false;
  79. }
  80. if ("commentViewModel" in continuationItems[0]) {
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86.  
  87. // package.json
  88. var package_default = {
  89. name: "return-youtube-comment-username",
  90. version: "0.6.0",
  91. devDependencies: {
  92. "@types/chrome": "^0.0.263",
  93. "@types/encoding-japanese": "^2.0.5",
  94. "@types/markdown-it": "^13.0.8",
  95. eslint: "^8.57.0",
  96. prettier: "^3.3.1",
  97. "ts-extension-builder": "^0.2.8",
  98. },
  99. license: "MIT",
  100. scripts: {
  101. "esbuild-register": "node --require esbuild-register",
  102. build: "npx crx-monkey build",
  103. dev: "npx crx-monkey dev",
  104. lint: "npx eslint --fix src/**/*.ts",
  105. },
  106. type: "module",
  107. dependencies: {
  108. "@mdit-vue/plugin-title": "^2.1.3",
  109. "@typescript-eslint/eslint-plugin": "^6.21.0",
  110. "@typescript-eslint/parser": "^6.21.0",
  111. "crx-monkey": "0.11.2",
  112. "encoding-japanese": "^2.2.0",
  113. "eslint-config-prettier": "^9.1.0",
  114. "markdown-it": "^14.1.0",
  115. typescript: "^5.4.5",
  116. },
  117. };
  118.  
  119. // src/utils/debugLog.ts
  120. function debugLog(message, value = "") {
  121. if (getRunningRuntime() === "Extension") {
  122. bypassSendMessage({
  123. type: "log",
  124. value: [`[rycu] ${message} %c${value}`, "color:cyan;"],
  125. });
  126. } else {
  127. console.log(`[rycu] ${message} %c${value}`, "color:cyan;");
  128. }
  129. }
  130. function debugErr(message) {
  131. console.error(`[rycu] ${message}`);
  132. if (getRunningRuntime() === "Extension") {
  133. bypassSendMessage({
  134. type: "err",
  135. value: [`[rycu] ${message}`],
  136. });
  137. }
  138. }
  139. function outputDebugInfo() {
  140. const logs = [""];
  141. const ytConf = window.yt.config_;
  142. if (ytConf !== void 0) {
  143. logs.push(
  144. "PAGE_BUILD_LABEL: " +
  145. (ytConf.PAGE_BUILD_LABEL !== void 0
  146. ? ytConf.PAGE_BUILD_LABEL
  147. : " undefined"),
  148. );
  149. logs.push(
  150. "INNERTUBE_CLIENT_VERSION: " +
  151. (ytConf.INNERTUBE_CLIENT_VERSION !== void 0
  152. ? ytConf.INNERTUBE_CLIENT_VERSION
  153. : " undefined"),
  154. );
  155. logs.push(
  156. "INNERTUBE_CONTEXT_CLIENT_VERSION: " +
  157. (ytConf.INNERTUBE_CONTEXT_CLIENT_VERSION !== void 0
  158. ? ytConf.INNERTUBE_CONTEXT_CLIENT_VERSION
  159. : " undefined"),
  160. );
  161. logs.push(
  162. "INNERTUBE_CONTEXT_GL: " +
  163. (ytConf.INNERTUBE_CONTEXT_GL !== void 0
  164. ? ytConf.INNERTUBE_CONTEXT_GL
  165. : " undefined"),
  166. );
  167. logs.push(
  168. "Browser: " +
  169. (ytConf.INNERTUBE_CONTEXT.client.browserName !== void 0
  170. ? ytConf.INNERTUBE_CONTEXT.client.browserName
  171. : " undefined"),
  172. );
  173. logs.push(
  174. "Is login: " +
  175. (ytConf.LOGGED_IN !== void 0
  176. ? `${ytConf.LOGGED_IN}`
  177. : " undefined"),
  178. );
  179. }
  180. logs.push(`Href: ${location.href}`);
  181. debugLog(
  182. `Return Youtube comment Username v${package_default.version}`,
  183. logs.join("\n"),
  184. );
  185. }
  186.  
  187. // src/utils/findElementByTrackingParams.ts
  188. function findElementByTrackingParams(trackingParams, elementSelector) {
  189. let returnElement = null;
  190. let errorAlerted = false;
  191. const elems = document.querySelectorAll(elementSelector);
  192. for (let i = 0; i < elems.length; i++) {
  193. if (
  194. elems[i]?.trackedParams === void 0 &&
  195. elems[i]?.polymerController?.trackedParams === void 0
  196. ) {
  197. debugErr(new Error("TrackedParams not found in element property."));
  198. }
  199. if (elems[i].trackedParams === trackingParams) {
  200. returnElement = elems[i];
  201. break;
  202. } else if (
  203. elems[i]?.polymerController?.trackedParams === trackingParams
  204. ) {
  205. returnElement = elems[i];
  206. break;
  207. } else {
  208. if (!errorAlerted) {
  209. void searchTrackedParamsByObject(trackingParams, elems[i]);
  210. errorAlerted = true;
  211. }
  212. }
  213. }
  214. return returnElement;
  215. }
  216. async function reSearchElement(trackingParams, selector) {
  217. return await new Promise((resolve) => {
  218. let isFinding = true;
  219. const search = () => {
  220. const el = findElementByTrackingParams(trackingParams, selector);
  221. if (el !== null) {
  222. resolve(el);
  223. isFinding = false;
  224. }
  225. if (isFinding) {
  226. setTimeout(() => {
  227. search();
  228. }, 100);
  229. }
  230. };
  231. search();
  232. });
  233. }
  234. function findElementAllByCommentId(commnetId, elementSelector) {
  235. const returnElements = [];
  236. const elems = document.querySelectorAll(elementSelector);
  237. for (let i = 0; i < elems.length; i++) {
  238. if (elems[i] !== void 0) {
  239. if (
  240. elems[i]?.__data?.data?.commentId === void 0 &&
  241. elems[i]?.polymerController?.__data?.data?.commentId === void 0
  242. ) {
  243. debugErr(new Error("Reply CommentId not found."));
  244. } else if (
  245. elems[i]?.__data?.data?.commentId !== void 0 &&
  246. elems[i].__data.data.commentId === commnetId
  247. ) {
  248. returnElements.push(elems[i]);
  249. } else if (
  250. elems[i]?.polymerController?.__data?.data?.commentId !== void 0 &&
  251. elems[i].polymerController.__data.data.commentId === commnetId
  252. ) {
  253. returnElements.push(elems[i]);
  254. }
  255. }
  256. }
  257. return returnElements;
  258. }
  259. async function reSearchElementAllByCommentId(commnetId, selector) {
  260. return await new Promise((resolve) => {
  261. let isFinding = true;
  262. const search = () => {
  263. const el = findElementAllByCommentId(commnetId, selector);
  264. if (el !== null) {
  265. resolve(el);
  266. isFinding = false;
  267. }
  268. if (isFinding) {
  269. setTimeout(() => {
  270. search();
  271. }, 100);
  272. }
  273. };
  274. search();
  275. });
  276. }
  277. async function searchTrackedParamsByObject(param, elem) {
  278. const elemObj = Object(elem);
  279. const search = (obj, history) => {
  280. Object.keys(obj).forEach((k) => {
  281. if (typeof obj[k] === "object") {
  282. search(obj[k], [...history, k]);
  283. } else if (obj[k] === param) {
  284. history.push(k);
  285. throw debugErr(
  286. new Error(`Unknown Object format!
  287. "${history.join(" > ")}"`),
  288. );
  289. }
  290. });
  291. };
  292. search(elemObj, []);
  293. }
  294.  
  295. // src/types/AppendContinuationItemsAction.ts
  296. function isReplyContinuationItemsV1(obj) {
  297. return Object.hasOwn(obj[0], "commentRenderer");
  298. }
  299. function isReplyContinuationItemsV2(obj) {
  300. return Object.hasOwn(obj[0], "commentViewModel");
  301. }
  302. function isConfinuationItemV2(obj) {
  303. return Object.hasOwn(obj, "commentViewModel");
  304. }
  305. function isConfinuationItemV1(obj) {
  306. return Object.hasOwn(obj, "comment");
  307. }
  308.  
  309. // src/utils/escapeString.ts
  310. function escapeString(text) {
  311. return text
  312. .replace(/</g, "&lt;")
  313. .replace(/>/g, "&gt;")
  314. .replace(/"/g, `&quot;`)
  315. .replace(/'/g, `&#39;`)
  316. .replace(/&/g, `&amp;`);
  317. }
  318. function decodeString(text) {
  319. return text
  320. .replace(/&lt;/g, "<")
  321. .replace(/&gt;/g, ">")
  322. .replace(/&quot;/g, `"`)
  323. .replace(/&#39;/g, `'`)
  324. .replace(/&amp;/g, `&`);
  325. }
  326.  
  327. // src/utils/getUserName.ts
  328. var isUseFeed = true;
  329. async function getUserName(id) {
  330. return new Promise((resolve) => {
  331. if (isUseFeed) {
  332. fetchFeed(id)
  333. .then((name) => {
  334. resolve(name);
  335. })
  336. .catch(() => {
  337. isUseFeed = false;
  338. debugErr(
  339. new Error("Catch Feed API Error, so change to Browse mode."),
  340. );
  341. fetchBrowse(id).then((name) => {
  342. resolve(name);
  343. });
  344. });
  345. } else {
  346. fetchBrowse(id).then((name) => {
  347. resolve(name);
  348. });
  349. }
  350. });
  351. }
  352. async function fetchFeed(id) {
  353. return await fetch(
  354. `https://www.youtube.com/feeds/videos.xml?channel_id=${id}`,
  355. {
  356. method: "GET",
  357. cache: "default",
  358. keepalive: true,
  359. },
  360. )
  361. .then(async (res) => {
  362. if (res.status !== 200)
  363. throw debugErr(
  364. new Error(`Feed API Error
  365. status: ${res.status}`),
  366. );
  367. return await res.text();
  368. })
  369. .then((text) => {
  370. const match = text.match("<title>([^<].*)</title>");
  371. if (match !== null) {
  372. return decodeString(match[1]);
  373. } else {
  374. debugErr("XML title not found");
  375. return "";
  376. }
  377. });
  378. }
  379. async function fetchBrowse(id) {
  380. return await fetch(
  381. `https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false`,
  382. {
  383. method: "POST",
  384. headers: {
  385. cache: "default",
  386. accept: "*/*",
  387. "accept-encoding": "gzip, deflate, br",
  388. "accept-language": "en",
  389. "content-type": "application/json",
  390. dnt: "1",
  391. referer: `https://www.youtube.com/channel/${id}`,
  392. },
  393. body: JSON.stringify({
  394. context: {
  395. client: {
  396. hl: window.yt.config_.HL,
  397. gl: window.yt.config_.GL,
  398. clientName: "WEB",
  399. clientVersion: "2.20230628.01.00",
  400. platform: "DESKTOP",
  401. acceptHeader:
  402. "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
  403. },
  404. user: { lockedSafetyMode: false },
  405. request: {
  406. useSsl: true,
  407. },
  408. },
  409. browseId: id,
  410. params: "EgVhYm91dPIGBAoCEgA%3D",
  411. }),
  412. },
  413. )
  414. .then(async (res) => {
  415. if (res.status !== 200)
  416. throw debugErr(
  417. new Error(`Browse API Error
  418. status: ${res.status}`),
  419. );
  420. return await res.json();
  421. })
  422. .then((text) => {
  423. const name = text.header.c4TabbedHeaderRenderer.title;
  424. return decodeString(name);
  425. });
  426. }
  427.  
  428. // src/rewrites/rewriteOfCommentRenderer/nameRewriteOfCommentRenderer.ts
  429. function nameRewriteOfCommentRenderer(
  430. commentRenderer,
  431. isNameContainerRender,
  432. userId,
  433. ) {
  434. const commentRendererBody =
  435. commentRenderer.__shady_native_children.namedItem("body");
  436. if (commentRendererBody === null) {
  437. throw debugErr(new Error("Comment renderer body is null."));
  438. }
  439. let nameElem = commentRendererBody.querySelector(
  440. "#main > #header > #header-author > h3 > a > yt-formatted-string",
  441. );
  442. if (isNameContainerRender) {
  443. const containerMain =
  444. commentRendererBody.__shady_native_children.namedItem("main");
  445. if (containerMain !== null) {
  446. nameElem = containerMain.querySelector(
  447. "#header > #header-author > #author-comment-badge > ytd-author-comment-badge-renderer > a > #channel-name > #container > #text-container > yt-formatted-string",
  448. );
  449. }
  450. }
  451. void getUserName(userId)
  452. .then((name) => {
  453. if (nameElem !== null) {
  454. if (nameElem.getAttribute("is-empty") !== null) {
  455. nameElem.removeAttribute("is-empty");
  456. }
  457. if (isNameContainerRender) {
  458. nameElem.textContent = escapeString(name);
  459. } else {
  460. nameElem.textContent = name;
  461. }
  462. } else {
  463. debugErr(new Error("Name element is null"));
  464. }
  465. })
  466. .catch((e) => {
  467. debugErr(e);
  468. });
  469. }
  470.  
  471. // src/rewrites/rewriteOfCommentRenderer/mentionRewriteOfCommentRenderer.ts
  472. function mentionRewriteOfCommentRenderer(commentRenderer) {
  473. const commentRendererBody =
  474. commentRenderer.__shady_native_children.namedItem("body");
  475. const main2 = commentRendererBody?.querySelector("#main");
  476. if (main2 !== void 0 && main2 !== null) {
  477. const aTags = main2.querySelectorAll(
  478. "#comment-content > ytd-expander > #content > #content-text > a",
  479. );
  480. for (let i = 0; i < aTags.length; i++) {
  481. if (aTags[i].getAttribute("href")?.match("/channel/.*") !== null) {
  482. const href = aTags[i].getAttribute("href");
  483. if (href !== null) {
  484. void getUserName(href.split("/")[2])
  485. .then((name) => {
  486. aTags[i].textContent = `@${name} `;
  487. })
  488. .catch((e) => {
  489. debugErr(e);
  490. });
  491. } else {
  492. debugErr(new Error("Mention Atag has not Href attr."));
  493. }
  494. }
  495. }
  496. }
  497. }
  498.  
  499. // src/rewrites/rewriteOfCommentRenderer/nameRewriteOfCommentViewModel.ts
  500. function nameRewriteOfCommentViewModel(commentViewModel) {
  501. const commentViewModelBody =
  502. commentViewModel.__shady_native_children.namedItem("body");
  503. if (commentViewModelBody === null) {
  504. throw debugErr(new Error("Comment view model body is null."));
  505. }
  506. if (!commentViewModelBodyGuard(commentViewModelBody)) {
  507. throw debugErr(
  508. new Error("The object format of comment view model is invalid."),
  509. );
  510. }
  511. const isNameContainerRender =
  512. commentViewModelBody.__shady.ea.__shady.ea.host.authorCommentBadge !==
  513. null;
  514. let nameElem = commentViewModelBody.querySelector(
  515. "#main > #header > #header-author > h3 > a > span",
  516. );
  517. const userId =
  518. commentViewModelBody.__shady.ea.__shady.ea.host.authorNameEndpoint
  519. .browseEndpoint.browseId;
  520. const userHandle =
  521. commentViewModelBody.__shady.ea.__shady.ea.host.authorNameEndpoint.browseEndpoint.canonicalBaseUrl.substring(
  522. 1,
  523. );
  524. if (isNameContainerRender) {
  525. const containerMain =
  526. commentViewModelBody.__shady_native_children.namedItem("main");
  527. if (containerMain !== null) {
  528. nameElem = containerMain.querySelector(
  529. "#header > #header-author > #author-comment-badge > ytd-author-comment-badge-renderer > a > #channel-name > #container > #text-container > yt-formatted-string",
  530. );
  531. }
  532. }
  533. void getUserName(userId)
  534. .then((name) => {
  535. if (nameElem !== null) {
  536. if (nameElem.getAttribute("is-empty") !== null) {
  537. nameElem.removeAttribute("is-empty");
  538. }
  539. let innerText = name;
  540. if (window.__rycu.settings.isShowNameToHandle) {
  541. innerText = decodeURI(userHandle) + ` ( ${name} )`;
  542. }
  543. if (window.__rycu.settings.isShowHandleToName) {
  544. innerText = name + ` ( ${decodeURI(userHandle)} )`;
  545. }
  546. if (isNameContainerRender) {
  547. nameElem.textContent = escapeString(innerText);
  548. } else {
  549. nameElem.textContent = innerText;
  550. }
  551. } else {
  552. debugErr(new Error("Name element is null"));
  553. }
  554. })
  555. .catch((e) => {
  556. debugErr(e);
  557. });
  558. }
  559. function commentViewModelBodyGuard(elem) {
  560. return Object.hasOwn(elem, "__shady");
  561. }
  562.  
  563. // src/rewrites/rewriteOfCommentRenderer/mentionRewriteOfCommentRendererV2.ts
  564. function mentionRewriteOfCommentRendererV2(commentRenderer) {
  565. const commentRendererBody =
  566. commentRenderer.__shady_native_children.namedItem("body");
  567. const main2 = commentRendererBody?.querySelector("#main");
  568. if (main2 !== void 0 && main2 !== null) {
  569. const aTags = main2.querySelectorAll(
  570. "#expander > #content > #content-text > span > span > a",
  571. );
  572. for (let i = 0; i < aTags.length; i++) {
  573. if (aTags[i].getAttribute("href")?.match("/channel/.*") !== null) {
  574. const href = aTags[i].getAttribute("href");
  575. if (href !== null) {
  576. void getUserName(href.split("/")[2])
  577. .then((name) => {
  578. aTags[i].textContent = `@${name} `;
  579. })
  580. .catch((e) => {
  581. debugErr(e);
  582. });
  583. } else {
  584. debugErr(new Error("Mention Atag has not Href attr."));
  585. }
  586. }
  587. }
  588. }
  589. }
  590.  
  591. // src/rewrites/reply.ts
  592. function rewriteReplytNameFromContinuationItems(continuationItems) {
  593. debugLog("Rewrite Reply.");
  594. if (isReplyContinuationItemsV1(continuationItems)) {
  595. debugLog("Rewrite reply of continuationItems.");
  596. for (let i = 0; i < continuationItems.length; i++) {
  597. const { commentRenderer } = continuationItems[i];
  598. if (commentRenderer !== void 0) {
  599. void getReplyElem(commentRenderer.trackingParams, "V1").then(
  600. (replyElem) => {
  601. reWriteReplyElem(replyElem, commentRenderer);
  602. },
  603. );
  604. }
  605. }
  606. }
  607. if (isReplyContinuationItemsV2(continuationItems)) {
  608. debugLog("Rewrite reply of comment view model.");
  609. for (let i = 0; i < continuationItems.length; i++) {
  610. const { commentViewModel } = continuationItems[i];
  611. if (commentViewModel !== void 0) {
  612. void getReplyElem(
  613. commentViewModel.rendererContext.loggingContext.loggingDirectives
  614. .trackingParams,
  615. "V2",
  616. ).then((replyElem) => {
  617. reWriteReplyElemV2(replyElem);
  618. });
  619. }
  620. }
  621. }
  622. }
  623. function reWriteReplyElem(replyElem, rendererData) {
  624. let isContainer = rendererData.authorIsChannelOwner;
  625. if (rendererData.authorCommentBadge !== void 0) {
  626. isContainer = true;
  627. }
  628. nameRewriteOfCommentRenderer(
  629. replyElem,
  630. isContainer,
  631. rendererData.authorEndpoint.browseEndpoint.browseId,
  632. );
  633. mentionRewriteOfCommentRenderer(replyElem);
  634. replyInputRewrite(replyElem);
  635. }
  636. function reWriteReplyElemV2(replyElem) {
  637. nameRewriteOfCommentViewModel(replyElem);
  638. mentionRewriteOfCommentRendererV2(replyElem);
  639. replyInputRewrite(replyElem);
  640. }
  641. async function getReplyElem(trackedParams, version) {
  642. return await new Promise((resolve) => {
  643. const selector =
  644. "#replies > ytd-comment-replies-renderer > #expander > #expander-contents > #contents > " +
  645. (version === "V1"
  646. ? "ytd-comment-renderer"
  647. : "ytd-comment-view-model");
  648. const commentRenderer = findElementByTrackingParams(
  649. trackedParams,
  650. selector,
  651. );
  652. if (commentRenderer !== null) {
  653. resolve(commentRenderer);
  654. } else {
  655. void reSearchElement(trackedParams, selector).then(
  656. (commentRenderer2) => {
  657. resolve(commentRenderer2);
  658. },
  659. );
  660. }
  661. });
  662. }
  663. function rewriteTeaserReplytNameFromContinuationItems(continuationItems) {
  664. debugLog("Rewrite teaser Reply.");
  665. for (let i = 0; i < continuationItems.length; i++) {
  666. if (isReplyContinuationItemsV1(continuationItems)) {
  667. debugLog("Teaser reply of continuationItems.");
  668. const { commentRenderer } = continuationItems[i];
  669. if (commentRenderer !== void 0) {
  670. void reSearchElementAllByCommentId(
  671. commentRenderer.commentId,
  672. "ytd-comment-replies-renderer > #teaser-replies > ytd-comment-renderer",
  673. ).then((replyElems) => {
  674. replyElems.forEach((replyElem) => {
  675. reWriteReplyElem(replyElem, commentRenderer);
  676. });
  677. });
  678. void reSearchElementAllByCommentId(
  679. commentRenderer.commentId,
  680. "ytd-comment-replies-renderer > #expander > #expander-contents > #contents > ytd-comment-renderer",
  681. ).then((replyElems) => {
  682. replyElems.forEach((replyElem) => {
  683. reWriteReplyElem(replyElem, commentRenderer);
  684. });
  685. });
  686. }
  687. }
  688. if (isReplyContinuationItemsV2(continuationItems)) {
  689. debugLog("Teaser reply of comment view model.");
  690. const { commentViewModel } = continuationItems[i];
  691. if (commentViewModel !== void 0) {
  692. const elem = findElementByTrackingParams(
  693. commentViewModel.rendererContext.loggingContext.loggingDirectives
  694. .trackingParams,
  695. "#teaser-replies > ytd-comment-view-model",
  696. );
  697. if (elem === null) {
  698. throw debugErr(
  699. new Error("Can not found Teaser Reply in V2 Elem."),
  700. );
  701. }
  702. reWriteReplyElemV2(elem);
  703. }
  704. }
  705. }
  706. }
  707. function replyInputRewrite(replyElem) {
  708. const replyToReplyBtn = replyElem.querySelector(
  709. "#reply-button-end > ytd-button-renderer",
  710. );
  711. const replyToReplyHander = () => {
  712. const replyLink = replyElem.querySelector("#contenteditable-root > a");
  713. const href = replyLink?.getAttribute("href");
  714. const channelId = href?.split("/")[2];
  715. if (channelId !== void 0 && replyLink !== null) {
  716. void getUserName(channelId).then((name) => {
  717. replyLink.textContent = ` @${name}`;
  718. });
  719. }
  720. replyToReplyBtn?.removeEventListener("click", replyToReplyHander);
  721. };
  722. replyToReplyBtn?.addEventListener("click", replyToReplyHander);
  723. document.addEventListener("rycu-pagechange", () => {
  724. replyToReplyBtn?.removeEventListener("click", replyToReplyHander);
  725. });
  726. }
  727.  
  728. // src/rewrites/comment.ts
  729. function rewriteCommentNameFromContinuationItems(continuationItems) {
  730. debugLog("Rewrite Comment.");
  731. for (let i = 0; i < continuationItems.length; i++) {
  732. if (continuationItems[i].commentThreadRenderer !== void 0) {
  733. void getCommentElem(
  734. continuationItems[i].commentThreadRenderer.trackingParams,
  735. ).then((commentElem) => {
  736. reWriteCommentElem(
  737. commentElem,
  738. continuationItems[i].commentThreadRenderer,
  739. );
  740. });
  741. const teaserContents =
  742. continuationItems[i].commentThreadRenderer.replies
  743. ?.commentRepliesRenderer.teaserContents;
  744. if (teaserContents !== void 0) {
  745. rewriteTeaserReplytNameFromContinuationItems(teaserContents);
  746. }
  747. }
  748. }
  749. }
  750. function reWriteCommentElem(commentElem, commentThreadRenderer) {
  751. const commentRenderer =
  752. commentElem.__shady_native_children.namedItem("comment");
  753. if (commentRenderer !== null && commentRenderer !== void 0) {
  754. if (isConfinuationItemV1(commentThreadRenderer)) {
  755. debugLog("Rewrite of Comment Renderer.");
  756. let isContainer =
  757. commentThreadRenderer.comment.commentRenderer.authorIsChannelOwner;
  758. if (
  759. commentThreadRenderer.comment.commentRenderer.authorCommentBadge !==
  760. void 0
  761. ) {
  762. isContainer = true;
  763. }
  764. nameRewriteOfCommentRenderer(
  765. commentRenderer,
  766. isContainer,
  767. commentThreadRenderer.comment.commentRenderer.authorEndpoint
  768. .browseEndpoint.browseId,
  769. );
  770. }
  771. if (isConfinuationItemV2(commentThreadRenderer)) {
  772. debugLog("Rewrite of Comment view model.");
  773. nameRewriteOfCommentViewModel(commentRenderer);
  774. }
  775. }
  776. }
  777. async function getCommentElem(trackingParams) {
  778. return await new Promise((resolve) => {
  779. const commentElem = findElementByTrackingParams(
  780. trackingParams,
  781. "#comments > #sections > #contents > ytd-comment-thread-renderer",
  782. );
  783. if (commentElem !== null) {
  784. resolve(commentElem);
  785. } else {
  786. void reSearchElement(trackingParams, "ytd-comment-thread-renderer")
  787. .then((commentElem2) => {
  788. resolve(commentElem2);
  789. })
  790. .catch((e) => {
  791. debugErr(e);
  792. });
  793. }
  794. });
  795. }
  796.  
  797. // src/handlers/handleYtAppendContinuationItemsAction.ts
  798. function handleYtAppendContinuationItemsAction(detail) {
  799. const continuationItems =
  800. detail.args[0].appendContinuationItemsAction.continuationItems;
  801. if (
  802. isCommentRenderer(continuationItems) ||
  803. isCommentRendererV2(continuationItems)
  804. ) {
  805. const replyDetail = detail;
  806. setTimeout(() => {
  807. rewriteReplytNameFromContinuationItems(
  808. replyDetail.args[0].appendContinuationItemsAction.continuationItems,
  809. );
  810. }, 100);
  811. } else {
  812. const commentDetail = detail;
  813. setTimeout(() => {
  814. rewriteCommentNameFromContinuationItems(
  815. commentDetail.args[0].appendContinuationItemsAction
  816. .continuationItems,
  817. );
  818. }, 400);
  819. }
  820. }
  821.  
  822. // src/handlers/handleYtCreateCommentAction.ts
  823. function handleYtCreateCommentAction(detail) {
  824. const createCommentDetail = detail;
  825. const continuationItems = [
  826. {
  827. commentThreadRenderer:
  828. createCommentDetail.args[0].createCommentAction.contents
  829. .commentThreadRenderer,
  830. },
  831. ];
  832. setTimeout(() => {
  833. rewriteCommentNameFromContinuationItems(continuationItems);
  834. }, 100);
  835. }
  836.  
  837. // src/handlers/handleYtCreateCommentReplyAction.ts
  838. function handleYtCreateCommentReplyAction(detail) {
  839. const createReplyDetail = detail;
  840. const continuationItems = [
  841. {
  842. commentRenderer:
  843. createReplyDetail.args[0].createCommentReplyAction.contents
  844. .commentRenderer,
  845. },
  846. ];
  847. setTimeout(() => {
  848. rewriteTeaserReplytNameFromContinuationItems(continuationItems);
  849. }, 100);
  850. }
  851.  
  852. // src/rewrites/highlightedReply.ts
  853. function rewriteHighlightedReply(trackedParams) {
  854. getReplyElem2(trackedParams, "V1").then((replyElem) => {
  855. reWriteReplyElemV2(replyElem);
  856. });
  857. }
  858. function rewriteHighlightedReplyV2(trackedParams) {
  859. getReplyElem2(trackedParams, "V2").then((replyElem) => {
  860. reWriteReplyElemV2(replyElem);
  861. });
  862. }
  863. async function getReplyElem2(trackedParams, version) {
  864. return await new Promise((resolve) => {
  865. const selector =
  866. "ytd-comment-replies-renderer > #teaser-replies > " +
  867. (version === "V1"
  868. ? "ytd-comment-renderer"
  869. : "ytd-comment-view-model");
  870. const commentRenderer = findElementByTrackingParams(
  871. trackedParams,
  872. selector,
  873. );
  874. if (commentRenderer !== null) {
  875. resolve(commentRenderer);
  876. } else {
  877. void reSearchElement(trackedParams, selector).then(
  878. (commentRenderer2) => {
  879. resolve(commentRenderer2);
  880. },
  881. );
  882. }
  883. });
  884. }
  885.  
  886. // src/handlers/handleYtGetMultiPageMenuAction.ts
  887. function handleYtGetMultiPageMenuAction(detail) {
  888. debugLog("handleYtGetMultiPageMenuAction");
  889. const getMultiPageMenuDetail = detail;
  890. const continuationItems =
  891. getMultiPageMenuDetail.args[0].getMultiPageMenuAction.menu
  892. .multiPageMenuRenderer.sections[1].itemSectionRenderer?.contents;
  893. const highLightedTeaserContents =
  894. getMultiPageMenuDetail.args[0]?.getMultiPageMenuAction?.menu
  895. ?.multiPageMenuRenderer.sections[1].itemSectionRenderer?.contents[0]
  896. ?.commentThreadRenderer.replies?.commentRepliesRenderer
  897. ?.teaserContents;
  898. if (continuationItems !== void 0) {
  899. setTimeout(() => {
  900. rewriteCommentNameFromContinuationItems(continuationItems);
  901. if (highLightedTeaserContents !== void 0) {
  902. debugLog("HighLighted Teaser Reply found.");
  903. if (isReplyContinuationItemsV1(highLightedTeaserContents)) {
  904. debugLog("highLighted Teaser Reply V1");
  905. const highLightedReplyRenderer =
  906. highLightedTeaserContents[0]?.commentRenderer;
  907. rewriteHighlightedReply(highLightedReplyRenderer.trackingParams);
  908. } else {
  909. debugLog("highLighted Teaser Reply V2");
  910. const commentViewModel =
  911. highLightedTeaserContents[0]?.commentViewModel;
  912. const trackingParams =
  913. commentViewModel.rendererContext.loggingContext
  914. .loggingDirectives.trackingParams;
  915. rewriteHighlightedReplyV2(trackingParams);
  916. }
  917. }
  918. }, 100);
  919. }
  920. }
  921.  
  922. // src/handlers/handleYtHistory.ts
  923. function handleYtHistory(detail) {
  924. const historyDetail = detail;
  925. const continuationItems =
  926. historyDetail.args[1].historyEntry?.rootData.response.contents
  927. .twoColumnWatchNextResults?.results?.results?.contents[3]
  928. ?.itemSectionRenderer?.contents;
  929. if (continuationItems !== void 0) {
  930. setTimeout(() => {
  931. rewriteCommentNameFromContinuationItems(continuationItems);
  932. }, 100);
  933. }
  934. }
  935.  
  936. // src/handlers/handleYtReloadContinuationItemsCommand.ts
  937. function handleYtReloadContinuationItemsCommand(detail) {
  938. const reloadDetail = detail;
  939. const { slot } = reloadDetail.args[0].reloadContinuationItemsCommand;
  940. if (slot === "RELOAD_CONTINUATION_SLOT_BODY") {
  941. const continuationItems =
  942. reloadDetail.args[0].reloadContinuationItemsCommand.continuationItems;
  943. if (continuationItems !== void 0) {
  944. setTimeout(() => {
  945. rewriteCommentNameFromContinuationItems(continuationItems);
  946. }, 100);
  947. }
  948. }
  949. }
  950.  
  951. // src/index.ts
  952. function main() {
  953. const settings = {
  954. isShowHandleToName: false,
  955. isShowNameToHandle: false,
  956. };
  957. window.__rycu = {
  958. settings,
  959. };
  960. if (getRunningRuntime() === "Extension") {
  961. bypassSendMessage(
  962. {
  963. type: "getShowHandleToName",
  964. value: null,
  965. },
  966. {},
  967. (isShowHandleToName) => {
  968. window.__rycu.settings.isShowHandleToName = isShowHandleToName;
  969. },
  970. );
  971. bypassSendMessage(
  972. {
  973. type: "getShowNameToHandle",
  974. value: null,
  975. },
  976. {},
  977. (isShowNameToHandle) => {
  978. window.__rycu.settings.isShowNameToHandle = isShowNameToHandle;
  979. },
  980. );
  981. }
  982. const handleYtAction = (e) => {
  983. switch (e.detail.actionName) {
  984. case "yt-append-continuation-items-action":
  985. handleYtAppendContinuationItemsAction(e.detail);
  986. break;
  987. case "yt-reload-continuation-items-command":
  988. handleYtReloadContinuationItemsCommand(e.detail);
  989. break;
  990. case "yt-history-load":
  991. handleYtHistory(e.detail);
  992. break;
  993. case "yt-get-multi-page-menu-action":
  994. handleYtGetMultiPageMenuAction(e.detail);
  995. break;
  996. case "yt-create-comment-action":
  997. handleYtCreateCommentAction(e.detail);
  998. break;
  999. case "yt-create-comment-reply-action":
  1000. handleYtCreateCommentReplyAction(e.detail);
  1001. break;
  1002. }
  1003. };
  1004. document.addEventListener("yt-action", handleYtAction);
  1005. document.addEventListener("yt-navigate-finish", () => {
  1006. document.dispatchEvent(new Event("rycu-pagechange"));
  1007. outputDebugInfo();
  1008. });
  1009. }
  1010. main();
  1011. })();
  1012. }
  1013.  
  1014. if (location.href.match("https://www.youtube.com/*") !== null) {
  1015. document.addEventListener("DOMContentLoaded", () => {
  1016. const script = document.createElement("script");
  1017. if (unsafeWindow.trustedTypes !== undefined) {
  1018. const policy = unsafeWindow.trustedTypes.createPolicy(
  1019. "crx-monkey-trusted-inject-policy",
  1020. { createScript: (input) => input },
  1021. );
  1022. script.text = policy.createScript(
  1023. script.text + `(${c3JjL2luZGV4LnRz.toString()})();`,
  1024. );
  1025. } else {
  1026. script.innerHTML =
  1027. script.innerHTML + `(${c3JjL2luZGV4LnRz.toString()})();`;
  1028. }
  1029. unsafeWindow.document.body.appendChild(script);
  1030. });
  1031. }