Ad Skip YT with Mute Ads

Play Youtube ads at 5x speed, skip ads after 6 seconds, and mute/unmute ads automatically.

// ==UserScript==
// @name         Ad Skip YT with Mute Ads
// @license      MIT
// @namespace    https://github.com/vncsmnl/
// @version      1.1
// @description  Play Youtube ads at 5x speed, skip ads after 6 seconds, and mute/unmute ads automatically.
// @author       vncsmnl
// @match        https://www.youtube.com/*
// @exclude      *://*.youtube.com/subscribe_embed?*
// @icon         https://media.cybernews.com/2023/02/no-ads-yt-supporting.png
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const targetNode = document.body;
    const config = { attributes: false, childList: true, subtree: true };

    // Função para mutar e desmutar anúncios
    const muteAd = (mute) => {
        const muteButton = document.querySelector('.ytp-mute-button');
        const muteIndicator = document.querySelector('.ytp-volume-slider-handle');
        const isMuted = muteIndicator && muteIndicator.style.left === '0px';

        if (mute && !isMuted) {
            
            muteButton.click();
        } else if (!mute && isMuted) {

            muteButton.click();
        }
    };

    // Função para pular anúncios e mutar durante os anúncios
    const skipAd = () => {
        const player = document.querySelector('.video-stream.html5-main-video');
        if (player) {
            player.playbackRate = 5;
           
            const skipButton = document.querySelector('.ytp-skip-ad-button');
            if (skipButton) {
                skipButton.click();
            }

            const previewAd = document.querySelector('.ytp-preview-ad');
            if (previewAd && player.currentTime > 6) {
                player.currentTime = player.duration;
            }

            muteAd(true);
        }
    };

    const callback = function(mutationsList, observer) {
        for (const mutation of mutationsList) {
            if (mutation.type === 'childList') {
                const adTextElements = document.querySelectorAll('.ytp-ad-text');
                if (adTextElements.length > 0) {
                    skipAd();
                } else {

                    muteAd(false);
                }
            }
        }
    };

    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);
})();