YouTube Subtitle Auto-Translator

Automatically translates YouTube subtitles to Japanese if they are in any other language

目前為 2024-06-10 提交的版本,檢視 最新版本

// ==UserScript==
// @name         YouTube Subtitle Auto-Translator
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Automatically translates YouTube subtitles to Japanese if they are in any other language
// @author       Aoi
// @match        https://www.youtube.com/*
// @grant        none
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    const googleTranslateUrl = 'https://translate.google.com/?sl=auto&tl=ja&text=';

    // Function to wait for an element to appear in the DOM
    function waitForElement(selector, callback) {
        const element = document.querySelector(selector);
        if (element) {
            callback(element);
        } else {
            setTimeout(() => waitForElement(selector, callback), 500);
        }
    }

    // Function to translate text using Google Translate web version
    async function translateText(text) {
        const response = await fetch(googleTranslateUrl + encodeURIComponent(text));
        const html = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const translatedText = doc.querySelector('.result-container').innerText;
        return translatedText;
    }

    // Function to observe and translate subtitles
    function observeSubtitles() {
        const observer = new MutationObserver(async mutations => {
            for (const mutation of mutations) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    const subtitleElement = mutation.addedNodes[0];
                    const subtitleText = subtitleElement.innerText;

                    // Only translate if the text is not in Japanese
                    if (subtitleText && !/[\u3040-\u30FF\uFF66-\uFF9F]/.test(subtitleText)) {
                        const translatedText = await translateText(subtitleText);
                        subtitleElement.innerText = translatedText;
                    }
                }
            }
        });

        waitForElement('.captions-text', subtitlesContainer => {
            observer.observe(subtitlesContainer, { childList: true, subtree: true });
        });
    }

    // Start observing subtitles when the video player is ready
    waitForElement('.html5-video-container', () => {
        observeSubtitles();
    });
})();