Google Auto Translate (Multilingual + Inline Translation)

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

Versione datata 10/03/2025. Vedi la nuova versione l'ultima versione.

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 (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);
})();