YouTube 一键截图

按 S 键截图

// ==UserScript==
// @name         YouTube 一键截图
// @description  按 S 键截图
// @version      1.1
// @author       DeepSeek
// @license      MIT
// @namespace    http://tampermonkey.net/
// @match        https://www.youtube.com/*
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';
    let videoElement = null;
    let isProcessing = false;

    // 初始化核心元素(新增重试机制)
    function initVideoElement() {
        if (!videoElement || videoElement?.readyState === 0) {
            videoElement = document.querySelector('video.html5-main-video') 
                || document.querySelector('video.stream-engine__video');
            
            // 如果仍然找不到,显示错误提示
            if (!videoElement) {
                console.error('[截图插件] 未找到视频元素');
                GM_notification({
                    title: '截图失败',
                    text: '无法定位视频元素,请刷新页面后重试',
                    timeout: 5000
                });
            }
        }
        return videoElement;
    }

    // 增强版截图功能
    async function captureScreenshot() {
        if (isProcessing) return;
        isProcessing = true;

        try {
            const video = initVideoElement();
            if (!video) return;

            // 检测视频可截图状态
            if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) {
                throw new Error('视频数据未准备好');
            }

            // 创建离屏canvas(绕过跨域限制)
            const canvas = new OffscreenCanvas(video.videoWidth, video.videoHeight);
            const ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0);

            // 异步获取Blob
            const blob = await canvas.convertToBlob({type: 'image/png'});
            const url = URL.createObjectURL(blob);

            // 生成文件名
            const title = document.title
                .replace(/( - YouTube)$/, '')
                .replace(/[<>:"/\\|?*]/g, '');
            const time = `${Math.floor(video.currentTime / 60)}-${Math.floor(video.currentTime % 60).toString().padStart(2, '0')}`;
            
            // 创建隐藏链接触发下载
            const link = document.createElement('a');
            link.download = `${title} ${time}.png`;
            link.href = url;
            document.body.appendChild(link);
            link.click();
            setTimeout(() => {
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }, 1000);

        } catch (error) {
            console.error('[截图插件] 错误详情:', error);
            GM_notification({
                title: '截图失败',
                text: `错误原因: ${error.message}`,
                timeout: 5000
            });
        } finally {
            isProcessing = false;
        }
    }

    // 键盘事件监听(兼容SPA)
    function handleKeyPress(event) {
        if (event.key.toLowerCase() === 's' && !event.target.closest('input, textarea')) {
            event.preventDefault();
            captureScreenshot();
        }
    }

    // 初始化(兼容YouTube动态加载)
    function init() {
        document.addEventListener('keydown', handleKeyPress);
        console.log('[截图插件] 已加载 - 按 S 键截图');
    }

    // 启动(等待页面完全加载)
    if (document.readyState === 'complete') {
        init();
    } else {
        window.addEventListener('load', init);
    }
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址