We have both a German and English version of our website with a manual language switcher installed. We would like to automatically re-direct traffic from Germany/Austria/Switzerland to the German language website by using the visitor's browser language settings. When we asked customer support, they replied we would need to use a Javascript Function. What's the best way of going about this?
const lang = navigator.language
if (lang.includes('de')) {
window.location = 'https://www.example.com/de'
}
The navigator language code for German in Germany/Austria/Switzerland all include 'de' (e.g. de-CH for Swiss German) so you just test if the navigator language includes that substring or not; if it does, load your German site.
I need quick help. I have a language switcher dropdown in my header. Now I want Automatic Redirect Based on Browser Language. Please share relevant js code related this.What I need is the possibility to redirect visitors to the appropriate language of my page. So if my browser is set to German language and I visit my site, I am automatically redirected to the German https://www.example.com/de/ site. If the browser settings are set to the English language, the visitor is automatically redirected to the https://www.example.com/enI have tried this but there is no luck.
$( document ).ready(function(){ var userLang = navigator.language || navigator.userLanguage; if (userLang == "de") { window.location.href = "https://www.example.com/de/" } });
Hmm...I don't see any reason why this wouldn't work (for German only, obviously, you haven't added English to this so if it's not working for your English pages that would be why). Where are you adding this code?
I have tried adding the code snippet to Settings > Pages > Templates > Site Header HTML. There I get this error:
When I try adding it to Site Footer HTML instead, I don't get an error, but it does not seem to do anything. When I browse to the English (primary language) page, it does not automatically switch to the german version.
@piersg thank you! I have now tried both scripts (inside script tags) and both were accepted by Hubspot. However, the first one doesn't do anything, and the second one (starting with the const statement) leads to a reload-loop of the page. It does switch to the German version, but than constantly and rapidly reloads the page and never stops doing so. Really odd.
Any ideas? If you don't have time for this, I would totally understand 🙂