Greasy Fork

Greasy Fork is available in English.

YouTube 双语字幕

通过菜单配置中文字体大小和Debug 日志开关

当前为 2026-03-25 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         YouTube 双语字幕
// @version      3.9
// @author       4Aiur
// @namespace    http://greasyfork.icu/zh-CN/users/394849-4aiur
// @description  通过菜单配置中文字体大小和Debug 日志开关
// @match        *://www.youtube.com/*
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_openInTab
// @run-at       document-idle
// @icon         https://www.youtube.com/s/desktop/b9bfb983/img/favicon_32x32.png
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const TARGET_LANG = 'zh-CN';
    const translationCache = new Map();
    const timers = new Map();

    // -------------------- 0. 中文与相似度检测函数 --------------------
    function isPureChinese(text){
        const cleaned=text.replace(/[\s\d\p{P}]/gu,'');
        if(!cleaned) return false;
        const chineseChars=cleaned.match(/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g)||[];
        return (chineseChars.length/cleaned.length)>0.8;
    }

    function isTooSimilar(s1,s2){
        const clean=s=>s.replace(/[\s\p{P}]/gu,'').toLowerCase();
        const c1=clean(s1),c2=clean(s2);
        return c1===c2||c1.includes(c2)||c2.includes(c1);
    }

    // -------------------- 1. 配置 & 菜单 --------------------
    let fontSize = GM_getValue('subtitle_font_size', 1.5);
    let isDebug = GM_getValue('debug_mode', false);

    const log = {
        info: (msg, ...args) => {
            if (isDebug) console.log(`%c[YouTube双语字幕]%c ${msg}`, 'color: #00bcd4; font-weight: bold', '', ...args);
        },
        warn: (msg, ...args) => {
            if (isDebug) console.warn(`[YouTube双语字幕] ${msg}`, ...args);
        },
        error: (msg, ...args) => {
            console.error(`[YouTube双语字幕] ${msg}`, ...args);
        }
    };

    log.info('脚本已执行', location.href);

    function registerMenu() {
        GM_registerMenuCommand(
            `⚙️ 设置中文字体大小 (当前: ${fontSize}em)`,
            () => {
                let newSize = prompt('请输入字体大小 (建议 1.1 - 2.0):', fontSize);
                if (newSize !== null) {
                    newSize = parseFloat(newSize);
                    if (!isNaN(newSize) && newSize > 0) {
                        fontSize = newSize;
                        GM_setValue('subtitle_font_size', newSize);
                        updateStyle();
                        location.reload();
                    }
                }
            }
        );

        GM_registerMenuCommand(
            isDebug ? '🚫 关闭调试日志 (当前: 开启)' : '🐞 开启调试日志 (当前: 关闭)',
            () => {
                isDebug = !isDebug;
                GM_setValue('debug_mode', isDebug);
                location.reload();
            }
        );

        GM_registerMenuCommand('💬 反馈 & 建议', () => {
            GM_openInTab(
                'http://greasyfork.icu/zh-CN/scripts/567512-youtube-%E4%B8%AD%E8%8B%B1%E5%8F%8C%E8%AF%AD%E5%AD%97%E5%B9%95/feedback',
                { active: true }
            );
        });
    }

    // -------------------- 2. Trusted Types --------------------
    let ttPolicy;
    if (window.trustedTypes && window.trustedTypes.createPolicy) {
        ttPolicy = window.trustedTypes.createPolicy(
            'youtube-dual-subtitles-policy',
            { createHTML: s => s }
        );
    }

    function setSafeContent(el, content) {
        if (!el) return;
        el.innerText = content;
    }

    // -------------------- 3. CSS --------------------
    function updateStyle() {
        document.getElementById('my-subtitle-style')?.remove();

        const css = `
        .ytp-caption-window-container .ytp-caption-window-bottom {
            width: 100% !important;
            left: 0 !important;
            margin-left: 0 !important;
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
            background: none !important;
            box-shadow: none !important;
        }

        .ytp-caption-window-container .caption-visual-line {
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
            justify-content: center !important;
            width: 100% !important;
            text-align: center !important;
        }

        .ytp-caption-segment {
            display: inline-block !important;
            padding: 2px 10px !important;
            text-align: center !important;
        }

        .my-trans-line {
            display: block !important;
            width: fit-content !important;
            margin: 4px auto !important;
            order: -1 !important;
            color: #FFCC00 !important;
            font-size: ${fontSize}em !important;
            font-weight: bold !important;
            line-height: 1.2 !important;
            min-height: 1.2em !important;
            white-space: nowrap !important;
            padding: 2px 8px !important;
            background: rgba(0, 0, 0, 0.7) !important;
            border-radius: 4px !important;
            text-align: center !important;
        }
        `;

        const style = document.createElement('style');
        style.id = 'my-subtitle-style';
        style.innerHTML = ttPolicy ? ttPolicy.createHTML(css) : css;
        document.head.appendChild(style);

        log.info('样式已加载');
    }

    // -------------------- 4. 翻译 --------------------
    async function translate(text) {
        if (!text || text.length < 2) return null;

        if (translationCache.has(text)) {
            log.info(`命中缓存: "${text.substring(0, 15)}..."`);
            return translationCache.get(text);
        }

        try {
            log.info(`发起请求: "${text.substring(0, 15)}..."`);
            const url =
                `https://translate.googleapis.com/translate_a/single` +
                `?client=gtx&sl=auto&tl=${TARGET_LANG}&dt=t&q=${encodeURIComponent(text)}`;

            const res = await fetch(url);
            const data = await res.json();

            if (data?.[0]) {
                const result = data[0].map(x => x[0]).join('');
                translationCache.set(text, result);
                return result;
            }
        } catch (e) {
            log.error('翻译异常:', e);
        }
        return null;
    }

    // -------------------- 5. 核心 --------------------
    function processLine(line) {
        const segments = line.querySelectorAll('.ytp-caption-segment');
        if (!segments.length) return;

        const fullText = Array.from(segments)
            .map(s => s.innerText)
            .join(' ')
            .replace(/\s+/g, ' ')
            .trim();

        if (!fullText) return;

        log.info(`处理字幕: ${fullText}`);

        if (line.dataset.lastText === fullText) return;
        line.dataset.lastText = fullText;

        if (isPureChinese(fullText)) {
            line.querySelector('.my-trans-line')?.remove();
            return;
        }

        let transDiv = line.querySelector('.my-trans-line');
        if (!transDiv) {
            transDiv = document.createElement('div');
            transDiv.className = 'my-trans-line';
            line.prepend(transDiv);
            log.info('DOM: 创建占位行');
        }

        if (translationCache.has(fullText)) {
            log.info(`命中缓存: "${fullText.substring(0, 15)}..."`);
            const cached = translationCache.get(fullText);

            if (!isTooSimilar(cached, fullText)) {
                setSafeContent(transDiv, cached);
            } else {
                transDiv.innerText = '\u00A0'; // 不可见占位
            }
            return;
        }

        clearTimeout(timers.get(line));

        const timer = setTimeout(async () => {
            if (!line.isConnected) return;

            const result = await translate(fullText);

            if (result && line.isConnected) {
                if (!isTooSimilar(result, fullText)) {
                    setSafeContent(transDiv, result);
                } else {
                    transDiv.innerText = '\u00A0'; // 不可见占位
                }
            }
        }, 200);

        timers.set(line, timer);
    }

    // -------------------- 6. 原 observer --------------------
    const observer = new MutationObserver(() => {
        document.querySelectorAll('.caption-visual-line').forEach(processLine);
    });

    let observerStarted = false;
    let initRetry = 0;

    function init() {
        const container = document.querySelector('.ytp-caption-window-container');

        if (!container) {
            if (initRetry++ < 20) {
                setTimeout(init, 500);
            } else {
                log.warn('字幕容器未找到,停止重试');
            }
            return;
        }

        initRetry = 0;

        if (!observerStarted) {
            log.info('初始化: 字幕容器已就绪');
            observer.observe(container, { childList: true, subtree: true });
            observerStarted = true;
        }
    }

    // -------------------- 全局 observer --------------------
    const globalObserver = new MutationObserver(() => {
        const lines = document.querySelectorAll('.caption-visual-line');
        if (!lines.length) return;

        log.info(`全局监听命中: ${lines.length} 行字幕`);

        lines.forEach(processLine);
    });

    globalObserver.observe(document.body, {
        childList: true,
        subtree: true
    });

    // -------------------- 启动 --------------------
    registerMenu();
    updateStyle();
    init();

    ['yt-navigate-finish', 'yt-page-data-updated'].forEach(evt => {
        window.addEventListener(evt, () => {
            log.info(`YouTube 事件: ${evt}`);
            observer.disconnect();
            observerStarted = false;
            timers.clear();
            init();
        });
    });

})();