使用Google翻译插件(IP和Accept-Language)自动翻译网站?

3
有没有一种方法可以使用Google翻译插件根据访问者的IP和“accept-language”标头信息自动翻译我的网站?谢谢!

1
使用IP是一个非常糟糕的想法,因为许多国家有多种官方语言,例如比利时、南非。 - Mousey
2
请查看此答案:https://dev59.com/vm7Xa4cB1Zd3GeqPo1g1 - Mousey
2个回答

3

这是一道老问题,不建议这样做(因为用户可以使用VPN),但我很无聊,所以我想到了以下解决方案:

代码:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script></head>
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>
<body>
    <center>
        <br/>
        <div id="google_translate_element"></div><br/>
        Country:&nbsp;<span id="country"></span>
        <h1>Hello my friends this is a cool code.</h1>
    </center>
    <script>
    function hc(dc){
        lang = Cookies.get('language');
        if(lang != dc){
            window.location.hash = 'googtrans(en|' + dc + ')';
            location.reload();
            Cookies.set('language', dc);
        }
    }
    $.ajax({
        type: "GET",
        url: "https://geolocation-db.com/jsonp/",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function( location ) {
            $('#country').html(location.country_code);
            co = location.country_code;
            co = co.toLowerCase();
            hc(co); // Replace here
        }
    });
    function googleTranslateElementInit() {
        new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
    }
    </script>
    <script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</body>
</html>

说明:

这个技术会向https://geolocation-db.com/(免费)发送Ajax请求,然后使用json响应中的国家代码,将哈希值替换为该国家代码,接着使用谷歌翻译进行翻译。现在这可能不是最好的方法,而且肯定存在问题,但它有时有效。

问题:

  • VPN
  • 一些国家,如美国,由于"us"不是语言代码,因此无法使用,您需要更改它。
  • 可能还有其他问题

试一试:

复制代码并尝试运行。如果您在美国或某些没有自己的语言代码的国家,请用您自己的测试语言代码替换 hc(co);,例如: hc('ru');

要求:

  • jQuery
  • JS-Cookie(非必需项,您可以自己编写没有此插件的代码)
  • Google翻译API(不用说)

有点有趣,这个问题在发布7年后才被接受回答... - John Doe

0
对于React用户来说,有一个React Hook可以使用Google翻译以简洁的方式轻松地翻译网页。
它可以让您的网页保持整洁,而不会有Google翻译小部件的混乱,并且非常可定制。
使用以下命令安装Hook库: npm install use-google-translate 示例用法:
import useGoogleTranslate from 'use-google-translate';


export default function Example() {

    const supportedLanguages = {
        en: {
            code: "en",//Required
            name: "English",//Optional
            isRTL: false,//Optional
            countryCode: "us"//Optional
        },
        "zh-CN": {
            code: "zh-CN",
            name: "中文",
            isRTL: false,
            countryCode: "cn"
        },
        ar: {
            code: "ar",
            name: "العربية",
            isRTL: true,
            countryCode: "sa"
        }
    }

    const futureTexts = [
        'This is an alert text that shows after clicking "Show Alert 1", and has been translated in the past for this time.',
        {
            id: 'show-alert-2', text: 'The is another alert text that shows after clicking "Show Alert 2", and has been translated in the past for this time.'
        }
    ]
    const mustTranslate = true

    const {
    lang,//current preferred, detected, or default language
    langs,//supportedLanguages
    isRTL,
    detectedCountryCode,
    supportsLanguage,
    getLanguageData,
    getTranslationFutureText,
    translate,
    translating,
    } = useGoogleTranslate(
        supportedLanguages, // *Required. The languages the translator should support

        "en", // *Required. The default language. This is also the language of the page

        // A text in the default language that the hook will add and hide as a div element to the page to detect when translation 
        // is done, by comparing the text content of this div on an interval of 200ms to this text.
        "Hello world", // *Required.

        // This are texts that will be displayed later. Such as in alert pop ups. 
        // The texts are added and hidden with unique ids as div elements to the page 
        // This allows the texts that will be needed in the lifespan of the page to be translated all at once, 
        // while the contents of these divs are returned with a simple function(getTranslationFutureText) when needed; 
        // to avoid layout change during user interactions that would cause another google translation process.
        futureTexts, 

        // If set to true, the page will reload when the translation has timed out without any translation done.
        // IF false, the translating state of will be set to false with no translation done.
        mustTranslate, // the default is true

        6000, // The translation process timeout in milliseconds. The default is 5000. That is, 5 seconds.
    );

    const handleAlert1 = () => {
        alert(getTranslationFutureText('This is an alert text that shows after clicking "Show Alert 1", and has been translated in the past for this time.'))
    }

    const handleAlert2 = () => {
        alert(getTranslationFutureText('show-alert-2'))
    }

    return (
        <div>
            <div style={{display: translating? "none" : "block"}}>
                <h1>This is a test content for translation.</h1>
                <div>Current language: {lang}</div>
                <select onChange={(e) => {
                    translate(e.value)
                }}>
                {Object.keys(langs || {}).map((lng) => {
                    if (lng === lang) return null;
                    return (
                        <option key={index} value={lang.code}>{lang.name}</option>
                    )
                })}
                </select>
                <button onClick={handleAlert1}>Show Alert 1</button><br />
                <button onClick={handleAlert2}>Show Alert 2</button>
            </div>
            <div style={{display: !translating? "none" : "block", fontStyle: "italic"}}>...</div>
        </div>
    )
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接