Is there a way to translate my website automatically based on the visitor's IP and "accept-language" header information using Google Translate Plug-in?
Thank you!
This is an old question, and it is not recommended at all to do this (since a user could just use a vpn) but I was bored so here is what I came up with:
Code:
<!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>
Explination:
Basically it sends an Ajax request to https://geolocation-db.com/ (free) and using the json response, it takes out the country code and then replaces the hash to the country code and google translate then translates it. Now this might not be the best way, and there are definitely problems to this, but it works (sometimes 😉).
Problems:
Try It Out:
Copy the code and try it out. If you are in the US or some other country that doesn't have it's own language code, to test it just replace the hc(co);
with your own testing language like hc('ru');
.
Requirements: