YouTube Ad Blocker (Updated)

Blocks YouTube ads effectively without detection.

  1. // ==UserScript==
  2. // @name YouTube Ad Blocker (Updated)
  3. // @namespace https://example.com/
  4. // @version 1.0
  5. // @description Blocks YouTube ads effectively without detection.
  6. // @author hunter
  7. // @match *://*.youtube.com/*
  8. // @grant GM_addStyle
  9. // @run-at document-end
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. const adSelectors = [
  16. '.ytp-ad-player-overlay',
  17. '.ytp-ad-module',
  18. '.ytp-ad-text',
  19. '.ad-interrupting',
  20. '.video-ads',
  21. '.ytp-ad-image-overlay'
  22. ];
  23.  
  24. const adPatterns = [
  25. 'googleads.g.doubleclick.net',
  26. 'youtube.com/api/stats/playback',
  27. 'youtube.com/get_video_info'
  28. ];
  29.  
  30. // Block network ads (fetch and XHR)
  31. const blockNetworkAds = () => {
  32. const originalFetch = window.fetch;
  33. window.fetch = function(url, options) {
  34. if (adPatterns.some(pattern => url.includes(pattern))) {
  35. console.log('Blocked fetch request:', url);
  36. return new Promise(() => {});
  37. }
  38. return originalFetch.apply(this, arguments);
  39. };
  40.  
  41. const originalXhrOpen = XMLHttpRequest.prototype.open;
  42. XMLHttpRequest.prototype.open = function(method, url) {
  43. if (adPatterns.some(pattern => url.includes(pattern))) {
  44. console.log('Blocked XMLHttpRequest:', url);
  45. return;
  46. }
  47. return originalXhrOpen.apply(this, arguments);
  48. };
  49. };
  50.  
  51. // MutationObserver to hide ads
  52. const observer = new MutationObserver(() => {
  53. adSelectors.forEach(selector => {
  54. document.querySelectorAll(selector).forEach(ad => {
  55. ad.style.display = 'none'; // Hide the ad instead of removing it
  56. });
  57. });
  58. });
  59.  
  60. const startObserver = () => {
  61. observer.observe(document.body, { childList: true, subtree: true });
  62. };
  63.  
  64. // Initialize the script after the video player is loaded
  65. const initializeObserver = () => {
  66. const player = document.querySelector('video');
  67. if (player) {
  68. startObserver();
  69. } else {
  70. setTimeout(initializeObserver, 1000); // Retry after 1 second if player isn't found
  71. }
  72. };
  73.  
  74. // Inject styles to hide ads without affecting the video player
  75. GM_addStyle(`
  76. ${adSelectors.filter(selector => !selector.includes('video')).join(', ')} {
  77. display: none !important;
  78. visibility: hidden !important;
  79. }
  80. `);
  81.  
  82. // Initialize the script
  83. blockNetworkAds();
  84. initializeObserver();
  85.  
  86. })();