AlexSJC
发布于 2023-04-03 / 5 阅读
1
0

YouTube 使用中文字幕

// ==UserScript==
// @name         YouTube 使用中文字幕
// @namespace    http://tampermonkey.net/
// @version      1.3.5
// @description  在 YouTube 上自动选择简体中文字幕
// @author       AlexSJC
// @match        https://www.youtube.com/*
// @icon         data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAOJJREFUSEvl1eENgjAQhuGXCXQEN9ARdBJ1M51ERtANHEEn0HzmzjTQxh6hv+w/CHxPrz1oR+PRNc5nCFyBdRA9AqfSO0PgFQz3x4tICahdunRCWWROQNWMkLmBEdICEPLNrQU2wB142K4ugRWgrkuH70kIUPjFgJ2l6VqArlMkDHi4ZnwGDgao7/dWUYqEgFK4L0kOCQM9sLAvVS2YDgeewNaWKgQoTFXkkFy4ng8DKaIu0kw1hGqTfeZe2STAkWZtGvn/Ta6gFvkjoHZJfh5kcxyZQ+Rm38/nfu3JNbmi5sAbHIBMGYWnrykAAAAASUVORK5CYII=
// @grant        none
// ==/UserScript==
 
(function () {
    const $ = document.querySelector.bind(document);
    const $$ = document.getElementsByClassName.bind(document);
 
    let video;
 
    if (!location.href.includes('watch')) {
        document.addEventListener('click', e => {
            console.log(e.target)
            if (e.target.closest('.ytd-rich-grid-media')) {
                setTimeout(listenVideo, 300)
            }
        }, true)
    } else {
        listenVideo()
    }
 
    function listenVideo() {
        video = $('video');
        video.addEventListener('canplay', () => {
            $('.ytp-ad-skip-button-icon')?.click();
        })
        video.addEventListener('loadeddata', clickToTranslate)
    }
 
    function checkAndClick() {
        const findElem = findElemByText.bind($$("ytp-menuitem"))
 
        const sub = findElem("字幕");
        if (!sub) return false;
        sub.click();
 
        const subc = findElem("中文");
        if (subc) {
            subc.click();
            video.click();
        } else {
            const autoTrans = findElem("自动翻译");
            if (!autoTrans) return false;
            autoTrans.click();
            const autoTransC = findElem("中文(简体)");
            if (!autoTransC) return false;
            autoTransC.click();
        }
        return true;
    }
 
    function findElemByText(text) {
        for (const elem of this) {
            if (elem.innerText.includes(text)) {
                return elem
            }
        }
        return null
    }
 
    function clickToTranslate() {
        $('.ytp-subtitles-button[aria-pressed="false"]')?.click();
        const settingsButton = $('.ytp-settings-button');
        settingsButton.click();
        if (!checkAndClick()) settingsButton.click();
    }
})();


评论