【问题标题】:Automatically Translate Website With Google Translate Plugin (IP & Accept-Language)?使用 Google 翻译插件(IP 和接受语言)自动翻译网站?
【发布时间】:2014-02-26 15:29:55
【问题描述】:

有没有办法使用谷歌翻译插件根据访问者的 IP 和“接受语言”标题信息自动翻译我的网站?

谢谢!

【问题讨论】:

标签: localization translation ip-address google-translate http-accept-language


【解决方案1】:

这是一个老问题,完全不建议这样做(因为用户可以只使用 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
  • 美国等一些国家/地区无法使用,因为“我们”不是语言代码,因此您必须更改它。
  • 可能还有其他问题

试试看:

复制代码并尝试一下。如果您在美国或其他没有自己的语言代码的国家/地区,要对其进行测试,只需将 hc(co); 替换为您自己的测试语言,例如 hc('ru');。

要求:

  • jQuery
  • JS-Cookie(不需要,不用这个插件也可以自己写代码)
  • Google 翻译 API(不废话)

【讨论】:

  • 有点有趣,这个问题在它提出大约 7 年后得到了接受......
【解决方案2】:

你可以在这里查看enter link description here 对于插件here,您将通过google获得源代码,您可以在其中根据您的要求设置默认语言。

function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'bn,en,gu,hi,ml,mr,pa,sd,si,ta,ur', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}

就像我已将“en”设置为默认语言。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多