Spotify Web Translator to English

Translate Spotify Web to English using DeepL

当前为 2024-08-05 提交的版本,查看 最新版本

// ==UserScript==
// @name         Spotify Web Translator to English
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Translate Spotify Web to English using DeepL
// @author       Inari
// @match        https://open.spotify.com/*
// @grant        none
// @icon         https://www.google.com/s2/favicons?sz=64&domain=spotify.com
// ==/UserScript==

(function() {
    'use strict';

    function waitForElement(selector, callback) {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                const element = document.querySelector(selector);
                if (element) {
                    observer.disconnect();
                    callback(element);
                }
            });
        });

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

    function translateText(text, callback) {
        const deeplURL = `https://www.deepl.com/translator#auto/en/${encodeURIComponent(text)}`;

        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        iframe.src = deeplURL;
        document.body.appendChild(iframe);

        iframe.onload = () => {
            setTimeout(() => {
                const translatedText = iframe.contentDocument.querySelector('.lmt__target_textarea').value;
                document.body.removeChild(iframe);
                callback(translatedText);
            }, 5000);
        };
    }

    function translatePage() {
        const textNodes = [];
        const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);

        let node;
        while (node = walker.nextNode()) {
            textNodes.push(node);
        }

        textNodes.forEach((textNode) => {
            const originalText = textNode.nodeValue.trim();
            if (originalText) {
                translateText(originalText, (translatedText) => {
                    textNode.nodeValue = translatedText;
                });
            }
        });
    }

    translatePage();

    waitForElement('.main-view-container__scroll-node', translatePage);

})();