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

Greasy fork 爱吃馍镜像

Google Auto Translate

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

スクリプトをインストールするには、Tampermonkey, GreasemonkeyViolentmonkey のような拡張機能のインストールが必要です。

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

スクリプトをインストールするには、TampermonkeyViolentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、TampermonkeyUserscripts のような拡張機能のインストールが必要です。

このスクリプトをインストールするには、Tampermonkeyなどの拡張機能をインストールする必要があります。

このスクリプトをインストールするには、ユーザースクリプト管理ツールの拡張機能をインストールする必要があります。

(ユーザースクリプト管理ツールは設定済みなのでインストール!)

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

公众号二维码

扫码关注【爱吃馍】

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

このスタイルをインストールするには、Stylusなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus などの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus tなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

(ユーザースタイル管理ツールは設定済みなのでインストール!)

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

公众号二维码

扫码关注【爱吃馍】

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

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください
// ==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();
        }
    });
})();