Greasy Fork is available in English.
Blocks YouTube ads effectively without detection.
当前为
// ==UserScript==
// @name YouTube Ad Blocker (Updated)
// @namespace https://example.com/
// @version 1.0
// @description Blocks YouTube ads effectively without detection.
// @author hunter
// @match *://*.youtube.com/*
// @grant GM_addStyle
// @run-at document-start
// ==/UserScript==
(function() {
'use strict';
// Selectors for common ad elements
const adSelectors = [
'.ytp-ad-player-overlay', // The overlay ad
'.ytp-ad-module', // The ad container
'.ytp-ad-text', // Text-based ads
'.ad-interrupting', // Popup or interrupting ads
'.video-ads', // Video ads container
'.ytp-ad-image-overlay' // Image-based overlay ads
];
// URL patterns for blocking network requests related to ads
const adPatterns = [
'googleads.g.doubleclick.net',
'youtube.com/api/stats/playback',
'youtube.com/get_video_info'
];
// MutationObserver to remove ads from the DOM
const observer = new MutationObserver(() => {
adSelectors.forEach(selector => {
document.querySelectorAll(selector).forEach(ad => ad.remove());
});
});
// Start observing the DOM for ads
const startObserver = () => {
observer.observe(document.body, {
childList: true,
subtree: true
});
};
// Block ad-related network requests by overriding fetch and XMLHttpRequest
const blockNetworkAds = () => {
// Override fetch
const originalFetch = window.fetch;
window.fetch = function(url, options) {
if (url && adPatterns.some(pattern => url.includes(pattern))) {
console.log('Blocked fetch request:', url);
return new Promise(() => {}); // Cancel the request
}
return originalFetch.apply(this, arguments);
};
// Override XMLHttpRequest
const originalXhrOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
if (adPatterns.some(pattern => url.includes(pattern))) {
console.log('Blocked XMLHttpRequest:', url);
return;
}
return originalXhrOpen.apply(this, arguments);
};
};
// Inject styles to hide ads that might be missed
GM_addStyle(`
${adSelectors.join(', ')} {
display: none !important;
visibility: hidden !important;
}
`);
// Initialize the script functionality
const initialize = () => {
startObserver();
blockNetworkAds();
};
// Run the script after the page has loaded
window.addEventListener('load', initialize);
})();