代码之家  ›  专栏  ›  技术社区  ›  olimits7

使用谷歌翻译插件(IP和接受语言)自动翻译网站?

  •  3
  • olimits7  · 技术社区  · 10 年前

    有没有一种方法可以使用Google translate插件根据访问者的IP和“接受语言”标题信息自动翻译我的网站?

    非常感谢。

    1 回复  |  直到 10 年前
        1
  •  3
  •   John Doe    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/ (免费)并使用json响应,它取出国家代码,然后将哈希替换为国家代码,谷歌翻译然后翻译它。现在这可能不是最好的方法,这肯定有问题,但它(有时)有效。

    问题 :

    • 虚拟专用网
    • 有些国家,比如美国,因为“我们”不是一种语言代码,所以你必须改变它。
    • 可能还有其他问题

    试试看 :

    复制代码并尝试。如果你在美国或其他没有自己语言代码的国家,测试它只需替换 hc(co); 使用您自己的测试语言 hc('ru'); .

    要求 :

    • jQuery
    • JS Cookie(不需要,您可以在没有此插件的情况下编写自己的代码)
    • 谷歌翻译API(No Duh)