Greasy Fork

YouTube广告加速跳过

自动检测YouTube广告,以16倍速加速播放并提示"正在跳过广告"

// ==UserScript==
// @name         YouTube广告加速跳过
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  自动检测YouTube广告,以16倍速加速播放并提示"正在跳过广告"
// @author       little fool
// @match        *://www.youtube.com/*
// @match        *://m.youtube.com/*
// @match        *://music.youtube.com/*
// @match        *://www.youtube-nocookie.com/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';
    
    // 创建提示元素
    const createNotification = () => {
        const notification = document.createElement('div');
        notification.id = 'yt-ad-skip-notification';
        notification.innerHTML = '正在跳过广告...';
        notification.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            font-family: Arial, sans-serif;
            font-size: 14px;
            z-index: 9999;
            display: none;
            border-left: 4px solid #ff4d4d;
        `;
        document.body.appendChild(notification);
        return notification;
    };
    
    const notification = createNotification();
    
    // 检测并处理广告
    const handleAds = () => {
        // 检查是否在播放广告
        const adShowing = document.querySelector('.ad-showing');
        const videoPlayer = document.querySelector('video');
        
        if (adShowing && videoPlayer) {
            // 显示提示
            notification.style.display = 'block';
            
            // 将广告加速到60倍速(实际限制为16倍)
            videoPlayer.playbackRate = 16;
            
            // 静音加速广告
            videoPlayer.muted = true;
            
            // 尝试点击跳过按钮
            const skipButton = document.querySelector('.ytp-ad-skip-button, .ytp-ad-skip-button-modern');
            if (skipButton) {
                skipButton.click();
            }
        } else {
            // 广告结束,隐藏提示并恢复正常速度
            notification.style.display = 'none';
            if (videoPlayer) {
                videoPlayer.playbackRate = 1;
                videoPlayer.muted = false;
            }
        }
    };
    
    // 使用MutationObserver监听DOM变化
    const observer = new MutationObserver(handleAds);
    
    // 配置观察选项
    const observerConfig = {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true
    };
    
    // 开始观察整个文档
    observer.observe(document.documentElement, observerConfig);
    
    // 初始检查
    handleAds();
    
    // 定期检查(作为备份)
    setInterval(handleAds, 1000);
    
    console.log('YouTube广告加速跳过脚本已启动');
})();