YouTube Ad Blocker (Updated)

Blocks YouTube ads effectively without detection.

目前为 2025-01-19 提交的版本。查看 最新版本

  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-start
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Selectors for common ad elements
  16. const adSelectors = [
  17. '.ytp-ad-player-overlay', // The overlay ad
  18. '.ytp-ad-module', // The ad container
  19. '.ytp-ad-text', // Text-based ads
  20. '.ad-interrupting', // Popup or interrupting ads
  21. '.video-ads', // Video ads container
  22. '.ytp-ad-image-overlay' // Image-based overlay ads
  23. ];
  24.  
  25. // URL patterns for blocking network requests related to ads
  26. const adPatterns = [
  27. 'googleads.g.doubleclick.net',
  28. 'youtube.com/api/stats/playback',
  29. 'youtube.com/get_video_info'
  30. ];
  31.  
  32. // MutationObserver to remove ads from the DOM
  33. const observer = new MutationObserver(() => {
  34. adSelectors.forEach(selector => {
  35. document.querySelectorAll(selector).forEach(ad => ad.remove());
  36. });
  37. });
  38.  
  39. // Start observing the DOM for ads
  40. const startObserver = () => {
  41. observer.observe(document.body, {
  42. childList: true,
  43. subtree: true
  44. });
  45. };
  46.  
  47. // Block ad-related network requests by overriding fetch and XMLHttpRequest
  48. const blockNetworkAds = () => {
  49. // Override fetch
  50. const originalFetch = window.fetch;
  51. window.fetch = function(url, options) {
  52. if (url && adPatterns.some(pattern => url.includes(pattern))) {
  53. console.log('Blocked fetch request:', url);
  54. return new Promise(() => {}); // Cancel the request
  55. }
  56. return originalFetch.apply(this, arguments);
  57. };
  58.  
  59. // Override XMLHttpRequest
  60. const originalXhrOpen = XMLHttpRequest.prototype.open;
  61. XMLHttpRequest.prototype.open = function(method, url) {
  62. if (adPatterns.some(pattern => url.includes(pattern))) {
  63. console.log('Blocked XMLHttpRequest:', url);
  64. return;
  65. }
  66. return originalXhrOpen.apply(this, arguments);
  67. };
  68. };
  69.  
  70. // Inject styles to hide ads that might be missed
  71. GM_addStyle(`
  72. ${adSelectors.join(', ')} {
  73. display: none !important;
  74. visibility: hidden !important;
  75. }
  76. `);
  77.  
  78. // Initialize the script functionality
  79. const initialize = () => {
  80. startObserver();
  81. blockNetworkAds();
  82. };
  83.  
  84. // Run the script after the page has loaded
  85. window.addEventListener('load', initialize);
  86. })();