有没有办法使用谷歌翻译插件根据访问者的 IP 和“接受语言”标题信息自动翻译我的网站?
谢谢!
有没有办法使用谷歌翻译插件根据访问者的 IP 和“接受语言”标题信息自动翻译我的网站?
谢谢!
这是一个老问题,根本不建议这样做(因为用户可以只使用 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');
.
要求:
您可以在此处查看在此处输入插件的链接描述 ,您将通过 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”设置为默认语言一样。