🎉 欢迎访问GreasyFork.Org 镜像站!本镜像站由公众号【爱吃馍】搭建,用于分享脚本。联系邮箱📮

Greasy fork 爱吃馍镜像

Google Auto Translate

Uses Google Translate widget first, only loading iframe if necessary.

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

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

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

🚀 安装遇到问题?关注公众号获取帮助

公众号二维码

扫码关注【爱吃馍】

回复【脚本】获取最新教程和防失联地址

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

🚀 安装遇到问题?关注公众号获取帮助

公众号二维码

扫码关注【爱吃馍】

回复【脚本】获取最新教程和防失联地址

// ==UserScript==
// @name         Google Auto Translate
// @namespace    https://greasyfork.org/en/users/1030895-universedev
// @author      UniverseDev
// @license     GPL-3.0-or-later
// @version      1.7
// @description  Uses Google Translate widget first, only loading iframe if necessary.
// @match        *://*/*
// @grant        unsafeWindow
// ==/UserScript==

(function () {
    "use strict";

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

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

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

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

    const insertGoogleTranslateWidget = () => {
        if (document.getElementById("google_translate_element")) return;

        const translateDiv = document.createElement("div");
        translateDiv.id = "google_translate_element";
        translateDiv.style = "position: fixed; bottom: 10px; right: 10px; z-index: 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);
    };

    unsafeWindow.googleTranslateInit = () => {
        new google.translate.TranslateElement(
            { pageLanguage: "auto", includedLanguages: getUserLanguage(), autoDisplay: true, multilanguagePage: true },
            "google_translate_element"
        );

        const translateWidget = document.querySelector(".goog-te-combo");
        if (translateWidget) {
            translateWidget.value = getUserLanguage();
            translateWidget.dispatchEvent(new Event("change"));
        }

        setTimeout(async () => {
            if (!isAlreadyTranslated() && (await shouldFallbackToIframe())) {
                createTranslateOverlay(getUserLanguage());
            }
        }, 5000); // Give time for widget translation
    };

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

        if (pageLang && pageLang.toLowerCase() === targetLang.toLowerCase()) return false;
        if (isAlreadyTranslated()) return false;

        return await canEmbedIframe();
    };

    const canEmbedIframe = () => {
        return new Promise((resolve) => {
            const testIframe = document.createElement("iframe");
            testIframe.style.display = "none";
            testIframe.src = "https://www.google.com"; // Safe test URL

            testIframe.onload = () => {
                document.body.removeChild(testIframe);
                resolve(true);
            };

            testIframe.onerror = () => {
                document.body.removeChild(testIframe);
                resolve(false);
            };

            document.body.appendChild(testIframe);
            setTimeout(() => {
                if (document.body.contains(testIframe)) {
                    document.body.removeChild(testIframe);
                    resolve(false);
                }
            }, 2000);
        });
    };

    const createTranslateOverlay = (targetLang) => {
        if (document.getElementById("googleTranslateIframe")) return;

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

        const iframe = document.createElement("iframe");
        Object.assign(iframe, {
            id: "googleTranslateIframe",
            src: translateUrl,
            style: "position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; border: none; z-index: 99999; background-color: #fff;",
        });

        document.body.appendChild(iframe);
    };

    window.addEventListener("load", () => {
        if (!isAlreadyTranslated()) {
            insertGoogleTranslateWidget();
        }
    });
})();