【发布时间】:2014-02-26 15:29:55
【问题描述】:
有没有办法使用谷歌翻译插件根据访问者的 IP 和“接受语言”标题信息自动翻译我的网站?
谢谢!
【问题讨论】:
-
使用 IP 是一个非常糟糕的主意,因为许多国家有多种官方语言,例如比利时、南非。
标签: localization translation ip-address google-translate http-accept-language
有没有办法使用谷歌翻译插件根据访问者的 IP 和“接受语言”标题信息自动翻译我的网站?
谢谢!
【问题讨论】:
标签: localization translation ip-address google-translate http-accept-language
这是一个老问题,完全不建议这样做(因为用户可以只使用 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: <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响应,取出国家代码,然后将哈希替换为国家代码,然后谷歌翻译然后翻译它。现在这可能不是最好的方法,这肯定有问题,但它有效(有时?)。
问题:
试试看:
复制代码并尝试一下。如果您在美国或其他没有自己的语言代码的国家/地区,要对其进行测试,只需将 hc(co); 替换为您自己的测试语言,例如 hc('ru');。
要求:
【讨论】:
你可以在这里查看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”设置为默认语言。
【讨论】: