Block Youtube Users

Hide videos of blacklisted users/channels and comments

As of 2025-05-30. See the latest version.

  1. // ==UserScript==
  2. // @name Block Youtube Users
  3. // @namespace https://codeberg.org/schegge
  4. // @description Hide videos of blacklisted users/channels and comments
  5. // @version 2.6
  6. // @author Schegge
  7. // @match https://www.youtube.com/*
  8. // @exclude *://*.youtube.com/embed/*
  9. // @exclude *://*.youtube.com/live_chat*
  10. // @run-at document-end
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_notification
  14. // @grant GM.getValue
  15. // @grant GM.setValue
  16. // @grant GM.notification
  17. // ==/UserScript==
  18.  
  19. // fix trusted-types https://github.com/Tampermonkey/tampermonkey/issues/1334#issuecomment-2556498540
  20. window.testTrusted = function() {
  21. if (typeof window != "undefined" &&
  22. ('trustedTypes' in window) &&
  23. ('createPolicy' in window.trustedTypes) &&
  24. (typeof window.trustedTypes.createPolicy == "function")) {
  25. window.trustedTypes.createPolicy('default', {createScriptURL: s => s, createScript: s => s, createHTML: s => s})
  26. } else {
  27. setTimeout(window.testTrusted, 1000);
  28. }
  29. }
  30. window.testTrusted();
  31.  
  32. // gm4 polyfill https://github.com/greasemonkey/gm4-polyfill
  33. if (typeof GM == 'undefined') {
  34. this.GM = {};
  35. Object.entries({
  36. 'GM_getValue': 'getValue',
  37. 'GM_setValue': 'setValue',
  38. 'GM_notification': 'notification'
  39. }).forEach(([oldKey, newKey]) => {
  40. let old = this[oldKey];
  41. if (old && (typeof GM[newKey] == 'undefined')) {
  42. GM[newKey] = function(...args) {
  43. return new Promise((resolve, reject) => { try { resolve(old.apply(this, args)); } catch (e) { reject(e); } });
  44. };
  45. }
  46. });
  47. }
  48.  
  49. (async function() {
  50.  
  51. /* VALUES */
  52.  
  53. const Values = {
  54. storageVer: '1',
  55. storageSep: ',',
  56. storageTimer: 1000,
  57. storageComment: '',
  58. storageVideo: '',
  59. storageAdd: '',
  60. storageHideShorts: '',
  61. storageBlacklist: [],
  62. storageWhitelist: [],
  63. menuOpen: false,
  64. menuPause: false
  65. };
  66.  
  67. // get saved values
  68. Values.storageVer = await GM.getValue('byuver', '1');
  69. Values.storageSep = await GM.getValue('sep', ',');
  70. Values.storageTimer = await GM.getValue('timer', 1000);
  71. Values.storageComment = await GM.getValue('hidecomments', '');
  72. Values.storageVideo = await GM.getValue('enablepause', '');
  73. Values.storageAdd = await GM.getValue('enableadd', '');
  74. Values.storageHideShorts = await GM.getValue('hideshorts', '');
  75. Values.storageBlacklist = getArray(await GM.getValue('savedblocks', ''));
  76. Values.storageWhitelist = getArray(await GM.getValue('savedwhites', ''));
  77.  
  78. // get array from string
  79. function getArray(string) {
  80. if (!string) return [];
  81. return string.split(Values.storageSep).map(v => v.trim()).filter(v => v.length);
  82. }
  83.  
  84. const Where = {
  85. renderer: `ytd-rich-item-renderer,
  86. ytd-video-renderer,
  87. ytd-channel-renderer,
  88. ytd-playlist-renderer,
  89. ytd-playlist-video-renderer,
  90. ytd-playlist-panel-video-renderer,
  91. ytd-movie-renderer,
  92. ytd-compact-video-renderer,
  93. ytd-compact-movie-renderer,
  94. ytd-compact-radio-renderer,
  95. ytd-compact-autoplay-renderer,
  96. ytd-compact-playlist-renderer,
  97. ytd-grid-video-renderer,
  98. ytd-grid-playlist-renderer,
  99. ytd-secondary-search-container-renderer,
  100. yt-lockup-view-model,
  101. ytd-video-owner-renderer
  102. ${Values.storageHideShorts ? ', ytd-reel-shelf-renderer' : ''}
  103. ${Values.storageComment ? ', ytd-comment-view-model.ytd-comment-replies-renderer, ytd-comment-view-model.ytd-comment-thread-renderer' : ''}`,
  104.  
  105. // home, related and page playlist: #metadata > :not([hidden]) #text.ytd-channel-name
  106. // ^ not hidden because of search video
  107. // search video: #channel-info #text.ytd-channel-name
  108. // search channel: #channel-title.ytd-channel-renderer span.ytd-channel-renderer, #info #text.ytd-channel-name, #metadata #subscribers.ytd-channel-renderer
  109. // video playlist: #byline.ytd-playlist-panel-video-renderer
  110. // playlists: .yt-content-metadata-view-model-wiz__metadata-row span.yt-core-attributed-string a[href^="/@"], .yt-content-metadata-view-model-wiz__metadata-row span.yt-core-attributed-string a[href^="/channel/"]
  111. // user video: #owner #upload-info #channel-name #text.ytd-channel-name, #meta #upload-info #channel-name #text.ytd-channel-name
  112. // comment: #author-text span.ytd-comment-view-model, #name #text.ytd-channel-name
  113. user: `#metadata > :not([hidden]) #text.ytd-channel-name,
  114. #channel-info #text.ytd-channel-name,
  115. #channel-title.ytd-channel-renderer span.ytd-channel-renderer,
  116. #info #text.ytd-channel-name,
  117. #metadata #subscribers.ytd-channel-renderer,
  118. #byline.ytd-playlist-panel-video-renderer,
  119. .yt-content-metadata-view-model-wiz__metadata-row span.yt-core-attributed-string a[href^="/@"],
  120. .yt-content-metadata-view-model-wiz__metadata-row span.yt-core-attributed-string a[href^="/channel/"],
  121. #owner #upload-info #channel-name #text.ytd-channel-name,
  122. #meta #upload-info #channel-name #text.ytd-channel-name
  123. ${Values.storageComment ? ', #author-text span.ytd-comment-view-model, #name #text.ytd-channel-name' : ''}`,
  124.  
  125. // if the above aren't found
  126. userFailSafe: 'a[href^="/@"], a[href^="/channel/"], .ytd-channel-name a',
  127.  
  128. shorts: 'a[href^="/shorts/"]',
  129.  
  130. videoPage: {
  131. parentId: 'owner',
  132. channel: '#owner #upload-info #channel-name #text.ytd-channel-name',
  133. video: '#player video.video-stream.html5-main-video'
  134. },
  135.  
  136. masthead: {
  137. parent: '#container.ytd-masthead',
  138. buttonsId: 'buttons'
  139. }
  140. };
  141.  
  142. /* INTERVAL FOR BLACKLISTING */
  143.  
  144. search();
  145. setInterval(search, Values.storageTimer);
  146.  
  147. /* CSS */
  148.  
  149. document.head.insertAdjacentHTML('beforeend', `<style>
  150. [data-block="yes"] { display: none!important; }
  151. .byu-add { float: left; margin-right: .4em; cursor: pointer; color: var(--yt-brand-youtube-red, red); font-size: .9em; background-color: var(--yt-spec-badge-chip-background); border-radius: 100%; width: 1.6em; text-align: center; font-weight: lighter; }
  152. #byu-icon { display: inline-block; position: relative; text-align: center; width: 40px; height: 24px; margin: 0 8px; font-weight: 100; }
  153. #byu-icon span { color: var(--yt-spec-icon-active-other); cursor: pointer; font-size: 20px; vertical-align: middle; }
  154. #byu-options { width: 400px; max-width: 80vw; display: flex; flex-flow: row wrap; align-items: baseline; position: fixed; right: 1em; padding: 1em; text-align: center; font-size: 1.2em; color: var(--yt-spec-text-primary); background-color: var(--yt-spec-menu-background); z-index: 99999; border-radius: 1em; box-shadow: 0 .3em 2em 0 var(--yt-spec-static-overlay-background-light); }
  155. #byu-options div { width: 33%; flex-grow: 1; box-sizing: border-box; padding: .6em; }
  156. #byu-save { font-weight: bold; cursor: pointer; color: var(--yt-brand-youtube-red, red); }
  157. #byu-pause { cursor: pointer; }
  158. #byu-options .byu-textarea { width: 100%; }
  159. #byu-options .byu-textarea span { width: 100%; text-align: center; font-weight: bold; }
  160. #byu-options .byu-textarea textarea { line-height: 1.2em; resize: vertical; width: 100%; padding: .4em; color: var(--yt-spec-text-primary); background-color: var(--yt-spec-badge-chip-background); box-sizing: border-box; border: 0; border-radius: 1em; }
  161. #byu-options .byu-textarea textarea#byu-blacklist { height: 8em; }
  162. #byu-options .byu-textarea textarea#byu-whitelist { height: 4em; }
  163. #byu-options input { color: var(--yt-spec-text-primary); background-color: var(--yt-spec-badge-chip-background); border: 0; padding: 0 2px; height: 1.6em; line-height: 1em; vertical-align: middle; box-sizing: border-box; Wmargin: 0; border-radius: .5em; }
  164. #byu-sep { width: 1em; }
  165. #byu-timer { width: 4.5em; }
  166. #byu-video-page-black { font-size: 1.2em; padding: var(--yt-button-padding); background: var(--yt-brand-youtube-red, red); color: #fff; border-radius: 2em; margin-right: .8em; font-weight: bold; }
  167. </style>`);
  168.  
  169. /* VIDEO FIRST PAGE */
  170.  
  171. if (Values.storageVideo && /\/watch/.test(window.location.href)) {
  172. let waitUserVideo = setInterval(() => {
  173. if (document.querySelector(Where.videoPage.channel)) {
  174. clearInterval(waitUserVideo);
  175.  
  176. let username = document.querySelector(Where.videoPage.channel).textContent.trim();
  177. if (ifMatch(username.toLowerCase())) {
  178. let video = document.querySelector(Where.videoPage.video);
  179. video.pause();
  180. video.currentTime = 0;
  181.  
  182. let divBlack = document.createElement('div');
  183. divBlack.id = 'byu-video-page-black';
  184. divBlack.title = username;
  185. divBlack.textContent = 'BLACKLISTED';
  186. document.getElementById(Where.videoPage.parentId).insertAdjacentElement('afterbegin', divBlack);
  187. }
  188. }
  189. }, 1000);
  190. }
  191.  
  192. /* BLACKLIST MENU */
  193.  
  194. document.body.insertAdjacentHTML('beforeend', `<div id="byu-options" style="display: none;">
  195. <div><span id="byu-save">SAVE</span></div>
  196. <div><span id="byu-pause">pause</span></div>
  197. <div class="byu-textarea"><span>blacklist</span>
  198. <textarea spellcheck="false" id="byu-blacklist">${Values.storageBlacklist.join(`${Values.storageSep} `)}</textarea></div>
  199. <div class="byu-textarea"><span>whitelist</span>
  200. <textarea spellcheck="false" id="byu-whitelist">${Values.storageWhitelist.join(`${Values.storageSep} `)}</textarea></div>
  201. <div title="separator between usernames">
  202. <input id="byu-sep" type="text" maxlength="1" value="${Values.storageSep}"> separator</div>
  203. <div title="interval between new checks in ms">
  204. <input id="byu-timer" type="number" min="500" max="5000" step="500" title="milliseconds" value="${Values.storageTimer}"> timer</div>
  205. <div title="always show x buttons">
  206. <input id="byu-enableadd" type="checkbox" value="clickadd" ${Values.storageAdd ? 'checked' : ''}> show buttons</div>
  207. <div title="hide comments from specific users">
  208. <input id="byu-hidecomments" type="checkbox" value="comments" ${Values.storageComment ? 'checked' : ''}> comments</div>
  209. <div title="from direct link if user is blacklisted">
  210. <input id="byu-enablepause" type="checkbox" value="pausevideo" ${Values.storageVideo ? 'checked' : ''}> pause video</div>
  211. <div title="hide all shorts">
  212. <input id="byu-hideshorts" type="checkbox" value="hideshorts" ${Values.storageHideShorts ? 'checked' : ''}> hide all shorts</div>
  213. </div>`);
  214.  
  215. // for the B wait till the masthead buttons are added
  216. const buttonB = document.createElement('div');
  217. buttonB.id = 'byu-icon';
  218. buttonB.innerHTML = '<span>B</span>';
  219.  
  220. let waitButton = setInterval(() => {
  221. if (document.getElementById(Where.masthead.buttonsId)) {
  222. clearInterval(waitButton);
  223. document.getElementById(Where.masthead.buttonsId).insertAdjacentElement('beforebegin', buttonB);
  224. document.head.insertAdjacentHTML('beforeend', `<style>#byu-options { top:${
  225. document.querySelector(Where.masthead.parent).offsetHeight
  226. }px; }</style>`);
  227. }
  228. }, 1000);
  229.  
  230. // open / close menu
  231. buttonB.addEventListener('click', openMenu);
  232. document.addEventListener('keydown', function(e) {
  233. if (e.ctrlKey && e.altKey && e.key == 'b') {
  234. openMenu();
  235. }
  236. });
  237.  
  238. function openMenu() {
  239. let byuOpts = document.getElementById('byu-options');
  240. byuOpts.style = byuOpts.style.display === 'none' ? '' : 'display: none;';
  241. buttonB.style.fontWeight = buttonB.style.fontWeight === '500' ? '' : '500';
  242.  
  243. Values.menuOpen = !Values.menuOpen;
  244. if (Values.storageAdd) return;
  245.  
  246. if (Values.menuOpen) {
  247. search();
  248. } else {
  249. document.querySelectorAll('.byu-add').forEach(el => el.parentElement.removeChild(el));
  250. }
  251. }
  252.  
  253. // save changes
  254. document.getElementById('byu-save').addEventListener('click', function() {
  255. if (/[*"]|^$/.test(document.getElementById('byu-sep').value)) {
  256. this.text('ERROR! separator');
  257. } else {
  258. Values.storageSep = document.getElementById('byu-sep').value;
  259. Values.storageTimer = Math.max(parseInt(document.getElementById('byu-timer').value, 10), 500) || 1000;
  260. Values.storageComment = document.getElementById('byu-hidecomments').checked ? 'yes' : '';
  261. Values.storageVideo = document.getElementById('byu-enablepause').checked ? 'yes' : '';
  262. Values.storageAdd = document.getElementById('byu-enableadd').checked ? 'yes' : '';
  263. Values.storageHideShorts = document.getElementById('byu-hideshorts').checked ? 'yes' : '';
  264. Values.storageBlacklist = getArray(document.getElementById('byu-blacklist').value.trim());
  265. Values.storageWhitelist = getArray(document.getElementById('byu-whitelist').value.trim());
  266. GM.setValue('sep', Values.storageSep);
  267. GM.setValue('timer', Values.storageTimer);
  268. GM.setValue('hidecomments', Values.storageComment);
  269. GM.setValue('enablepause', Values.storageVideo);
  270. GM.setValue('enableadd', Values.storageAdd);
  271. GM.setValue('hideshorts', Values.storageHideShorts);
  272. GM.setValue('savedblocks', Values.storageBlacklist.join(`${Values.storageSep} `));
  273. GM.setValue('savedwhites', Values.storageWhitelist.join(`${Values.storageSep} `));
  274. this.textContent = 'SAVED';
  275. search(true);
  276. }
  277. setTimeout(() => this.textContent = 'SAVE', 2000);
  278. });
  279.  
  280. // pause
  281. document.getElementById('byu-pause').addEventListener('click', function() {
  282. Values.menuPause = !Values.menuPause;
  283. if (Values.menuPause) {
  284. document.querySelectorAll('[data-block="yes"]').forEach(el => el.dataset.block = '');
  285. this.textContent = 'paused';
  286. } else {
  287. search(true);
  288. this.textContent = 'pause';
  289. }
  290. });
  291.  
  292. /* BLACKLISTING FUNCTIONS */
  293.  
  294. // global search
  295. function search(blacklistChanged = false) {
  296. for (el of document.querySelectorAll(Where.renderer)) {
  297. // hide shorts if option is enabled
  298. if (Values.storageHideShorts &&
  299. !Values.menuPause &&
  300. el.querySelector(Where.shorts)) {
  301.  
  302. if (el.dataset.block !== 'yes') el.dataset.block = 'yes';
  303. continue;
  304. }
  305.  
  306. // check if blacklisted
  307. findMatch(el, blacklistChanged);
  308. }
  309. }
  310.  
  311. // check if blacklisted, get username, add "x" buttons
  312. function findMatch(el, blacklistChanged) {
  313. let addButton = true;
  314.  
  315. // retrieve current username
  316. let userEl = el.querySelector(Where.user);
  317. let username = userEl?.textContent?.trim();
  318. if (!username) {
  319. // to try to not make the script completely break if yt changes
  320. // search with broader classes but don't add "x" buttons
  321. username = el.querySelector(Where.userFailSafe)?.textContent?.trim();
  322. if (!username) return;
  323. addButton = false;
  324. };
  325. username = username.toLowerCase();
  326.  
  327. // add "x" when menu is open or always add selected
  328. if (addButton &&
  329. (Values.menuOpen || Values.storageAdd) &&
  330. !el.querySelector('.byu-add')) {
  331.  
  332. let addBtn = document.createElement('div');
  333. addBtn.className = 'byu-add';
  334. addBtn.textContent = 'x';
  335. addBtn.addEventListener('click', addToBlacklist);
  336. userEl.insertAdjacentElement('beforebegin', addBtn);
  337. }
  338.  
  339. // if blacklist is paused, stop
  340. if (Values.menuPause) return;
  341.  
  342. // if blacklist or content are changed
  343. if (blacklistChanged || el.dataset.username !== username) {
  344. el.dataset.username = username;
  345.  
  346. // hide if match
  347. if (ifMatch(username)) {
  348. el.dataset.block = 'yes';
  349. // show if it was hidden with another username or deleted username from blacklist
  350. } else if (el.dataset.block) {
  351. el.dataset.block = '';
  352. }
  353. }
  354. }
  355.  
  356. // check if it needs to be blacklisted
  357. function ifMatch(u) {
  358. return (
  359. !Values.storageWhitelist.some(w => u === w.toLowerCase()) &&
  360. Values.storageBlacklist.some(b => {
  361. b = b.toLowerCase();
  362. if (b.startsWith('*')) {
  363. b = b.replace('*', '');
  364. return b && u.includes(b);
  365. } else {
  366. return u === b;
  367. }
  368. })
  369. );
  370. }
  371.  
  372. // add usernames to blacklist
  373. function addToBlacklist(e) {
  374. e.preventDefault();
  375. e.stopPropagation();
  376.  
  377. let username = this.nextElementSibling.textContent.trim().toLowerCase();
  378.  
  379. if (!Values.storageBlacklist.includes(username)) {
  380. Values.storageBlacklist.push(username);
  381. let blacks = Values.storageBlacklist.join(`${Values.storageSep} `);
  382. document.getElementById('byu-blacklist').value = blacks;
  383. GM.setValue('savedblocks', blacks);
  384. search(true);
  385. }
  386. }
  387.  
  388. /* NEW VERSION NOTIFICATION */
  389.  
  390. if (Values.storageVer !== '2.6') {
  391. Values.storageVer = '2.6';
  392. GM.setValue('byuver', Values.storageVer);
  393.  
  394. GM.notification({
  395. text: 'From now on, you have to click on the \"x\" buttons, not right-click on them + Option added to hide all shorts.',
  396. title: 'BLOCK YOUTUBE USERS [2.6]'
  397. });
  398. }
  399.  
  400. })();