Google Auto Translate (Multilingual + Inline Translation)

Auto-translates pages using an iframe overlay and inline Google Translate.

当前为 2025-03-10 提交的版本,查看 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Google Auto Translate (Multilingual + Inline Translation)
// @namespace    https://greasyfork.org/en/users/1030895-universedev
// @author      UniverseDev
// @license     GPL-3.0-or-later
// @version      1.2
// @description  Auto-translates pages using an iframe overlay and inline Google Translate.
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function () {
    "use strict";

    const STORAGE_KEY = "userTranslateLang";
    const DEFAULT_LANG = "en";

    const getUserLanguage = () => localStorage.getItem(STORAGE_KEY) || DEFAULT_LANG;

    const setUserLanguage = (lang) => {
        localStorage.setItem(STORAGE_KEY, lang);
        location.reload();
    };

    const detectPageLanguage = () =>
        document.documentElement.lang || document.querySelector("html")?.getAttribute("lang") || null;

    const isAlreadyTranslated = () => {
        return document.querySelector("body").classList.contains("translated-ltr") ||
               document.querySelector("body").classList.contains("translated-rtl");
    };

    // Check if iframe embedding is allowed (try to load it and handle error)
    const canEmbedIframe = (url) => {
        const iframe = document.createElement("iframe");
        iframe.style.display = "none";  // Hide the iframe
        iframe.src = url;

        return new Promise((resolve, reject) => {
            iframe.onload = () => resolve(true);
            iframe.onerror = () => reject(false);

            // Try to append iframe and check if it successfully loads
            document.body.appendChild(iframe);

            // Clean up after test
            setTimeout(() => {
                document.body.removeChild(iframe);
            }, 2000);
        });
    };

    const createTranslateOverlay = async (targetLang) => {
        const pageLang = detectPageLanguage();
        if (pageLang && pageLang.toLowerCase() === targetLang.toLowerCase()) {
            return;
        }

        const translateUrl = `https://translate.google.com/translate?hl=${targetLang}&sl=auto&tl=${targetLang}&u=${encodeURIComponent(location.href)}`;

        // Check if iframe can be embedded on this page
        const canEmbed = await canEmbedIframe(translateUrl);
        if (!canEmbed) {
            console.log("Iframe embedding is not allowed on this page.");
            return;
        }

        // Proceed with creating the iframe if embedding is allowed
        if (document.getElementById("googleTranslateIframe")) return;
        const iframe = document.createElement("iframe");
        iframe.id = "googleTranslateIframe";
        iframe.src = translateUrl;
        Object.assign(iframe.style, {
            position: "fixed",
            top: 0,
            left: 0,
            width: "100vw",
            height: "100vh",
            border: "none",
            zIndex: 99999,
            backgroundColor: "#fff",
        });
        document.body.appendChild(iframe);
    };

    const insertGoogleTranslateWidget = () => {
        // Check if the Google Translate widget script is allowed (if it can be loaded)
        if (document.querySelector("script[src*='translate_a/element.js']")) {
            return;
        }

        // Insert the widget script if it can be loaded
        const translateDiv = document.createElement("div");
        translateDiv.id = "google_translate_element";
        Object.assign(translateDiv.style, {
            position: "fixed",
            bottom: "10px",
            right: "10px",
            zIndex: 100000,
        });
        document.body.appendChild(translateDiv);

        const script = document.createElement("script");
        script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateInit";
        document.body.appendChild(script);
    };

    // Automatically trigger the Google Translate widget to translate the page
    window.googleTranslateInit = () => {
        new google.translate.TranslateElement(
            { pageLanguage: "auto", includedLanguages: getUserLanguage(), autoDisplay: true, multilanguagePage: true },
            "google_translate_element"
        );

        // Automatically select the target language and trigger translation
        const targetLang = getUserLanguage();
        const iframe = document.querySelector("iframe.goog-te-banner-frame");
        if (iframe) {
            const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
            const langSelect = iframeDocument.querySelector("select.goog-te-combo");
            if (langSelect) {
                langSelect.value = targetLang;
                langSelect.dispatchEvent(new Event("change"));
            }
        }
    };

    const autoTranslateIfNeeded = async () => {
        const targetLang = getUserLanguage();
        const pageLang = detectPageLanguage();

        // Delay trigger to ensure the page has loaded and to avoid issues with redirection
        if (document.readyState === "complete" && (!pageLang || pageLang.toLowerCase() !== targetLang.toLowerCase()) && !isAlreadyTranslated()) {
            await createTranslateOverlay(targetLang);
        } else {
            await insertGoogleTranslateWidget();
        }
    };

    // Add a delay to prevent premature translation triggering
    setTimeout(autoTranslateIfNeeded, 1000); // Delay execution by 1 second

    // Listen for load event as a fallback if readyState is not 'complete'
    window.addEventListener("load", autoTranslateIfNeeded);
})();