localization - 使用 Google 翻译插件自动翻译网站(IP 和接受语言)?

有没有办法使用 Google 翻译插件根据访问者的 IP 和“accept-language” header 信息自动翻译我的网站?

谢谢!

最佳答案

这是一个老问题,根本不建议这样做(因为用户可以只使用 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 响应,它取出国家代码,然后将哈希替换为国家代码,谷歌翻译然后翻译它。现在这可能不是最好的方法,而且肯定有问题,但它有效(有时

相关文章:

ruby-on-rails - 在 rails 开发环境 smtp cpanel 上发送电子邮件 r

Django 1.6 - 如何将显示的文本缩短到模板中?

qt - 如何动态创建Q_Properties

math - 最大化受二次约束的线性目标

Django - 如何设置表单字段占位符的样式?

arrays - 简单数组追加操作的时间复杂度

asp.net-mvc - MVC 层和 DAL 和数据层

lua - 什么 lua 功能可以用作 python 或 tcl expect 中的 pexpect

command-line - 无法在 cygwin 上运行 isql

jdbc - 在 Netty 消息处理中使用 JDBC 事务