YouTube Code Highlighter

Highlight code in YouTube comments

当前为 2025-03-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Code Highlighter
  3. // @namespace https://greasyfork.org/ru/users/901750-gooseob
  4. // @version 1.1.1
  5. // @description Highlight code in YouTube comments
  6. // @author GooseOb
  7. // @license MIT
  8. // @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js
  9. // @match https://www.youtube.com/*
  10. // @icon https://www.google.com/s2/favicons?sz=64&domain=youtube.com
  11. // ==/UserScript==
  12.  
  13. (function(){// index.ts
  14. var until = (getItem, check, msToWait = 1e4, msReqTimeout = 20) => new Promise((res, rej) => {
  15. const reqLimit = msToWait / msReqTimeout;
  16. let i = 0;
  17. const interval = setInterval(() => {
  18. if (i++ > reqLimit)
  19. exit(rej);
  20. const item = getItem();
  21. if (!check(item))
  22. return;
  23. exit(() => res(item));
  24. }, msReqTimeout);
  25. const exit = (cb) => {
  26. clearInterval(interval);
  27. cb();
  28. };
  29. });
  30. var untilAppear = (getItem, msToWait) => until(getItem, Boolean, msToWait);
  31. untilAppear(() => document.getElementById("comments")).then((comments) => {
  32. let isCSSLoaded = false;
  33. const visitedComments = new Set;
  34. const loadCSS = () => {
  35. fetch("https://cdn.jsdelivr.net/npm/highlight.js/styles/atom-one-dark.css").then((r) => r.text()).then((cssText) => {
  36. const style = document.createElement("style");
  37. style.innerHTML = cssText;
  38. document.head.appendChild(style);
  39. });
  40. };
  41. const _highlighter = {
  42. createHTML: (code) => code.replace(/```(\S*)\n(.+?)```/gs, (_$0, $1, $2) => `<code>\`\`\`${$1}
  43. ${($1 ? hljs.highlight($2, { language: $1 }) : hljs.highlightAuto($2)).value}\`\`\`</code>`)
  44. };
  45. const highlighter = window.trustedTypes?.createPolicy?.("highlightedCode", _highlighter) || _highlighter;
  46. setInterval(() => {
  47. for (const comment of comments.querySelectorAll("ytd-comment-view-model #content .yt-core-attributed-string")) {
  48. if (!visitedComments.has(comment) && /```\S*\n/.test(comment.textContent)) {
  49. visitedComments.add(comment);
  50. if (!isCSSLoaded) {
  51. loadCSS();
  52. isCSSLoaded = true;
  53. }
  54. comment.innerHTML = highlighter.createHTML(comment.textContent);
  55. }
  56. }
  57. }, 3000);
  58. });
  59. })()