Lightweight YouTube AdBlock

Blocks ads on YouTube without eating up your resources

2023-05-20 기준 버전입니다. 최신 버전을 확인하세요.

// ==UserScript==
// @name         Lightweight YouTube AdBlock
// @version      1.2
// @description  Blocks ads on YouTube without eating up your resources
// @author       equmaq
// @match        https://www.youtube.com/*
// @license      MIT
// @namespace https://greasyfork.org/users/990886
// ==/UserScript==

(function() {
    'use strict';

    // Function to remove YouTube video ads and specified element
    function removeAds() {
        // Remove the video ads
        var ads = document.querySelectorAll('.ad-showing');
        ads.forEach(function(ad) {
            ad.remove();
        });

        // Remove the overlay ads
        var overlays = document.querySelectorAll('.ytp-ad-overlay-slot');
        overlays.forEach(function(overlay) {
            overlay.remove();
        });

        // Remove the specified element by full XPath
        var targetElement = document.evaluate("/html/body/ytd-app/div[1]/ytd-page-manager/ytd-browse/ytd-two-column-browse-results-renderer/div[1]/ytd-rich-grid-renderer/div[3]/ytd-banner-promo-renderer", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
        if (targetElement) {
            targetElement.remove();
        }

        // Resume video playback if paused due to an ad
        var player = document.querySelector('video');
        if (player && player.paused) {
            player.play();
        }
    }

    // Mutation observer to detect and remove new ads
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            var addedNodes = mutation.addedNodes;
            for (var i = 0; i < addedNodes.length; i++) {
                var node = addedNodes[i];
                if (node.classList && (node.classList.contains('ad-showing') || node.classList.contains('ytp-ad-overlay-slot'))) {
                    removeAds();
                }
            }
        });
    });

    // Configuration of the mutation observer
    var config = { childList: true, subtree: true };

    // Start observing the changes
    observer.observe(document.body, config);

    // Remove ads on initial page load
    removeAds();
})();