Google Auto Translate (Multilingual + Inline Translation)

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

目前為 2025-03-10 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 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);
})();