有没有办法使用 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: <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 响应,它取出国家代码,然后将哈希替换为国家代码,谷歌翻译然后翻译它。现在这可能不是最好的方法,而且肯定有问题,但它有效(有时