0

It is very hard to find any useful code to a working JavaScript Code, that redirects the user to the .html file of their browser language preference. So I have a website which is named index.html and it is in english. And then I have another website in a folder de/index.html which is in german. I want to redirect the user to the german website if he has set his browser language preference to german and let him stay on the english website if he has any other language set as his preference.

|-index.html
|-de
  |-index.html
  • A link to useful skripts would also help :) – Alexgamer470 Mar 02 '21 at 11:00
  • 1
    Redirecting should be no problem with `window.location.replace()`, for detecting the browser language I've found this SO question, maybe it will help you: https://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference – Alex Berger Mar 02 '21 at 11:05

1 Answers1

1
<script type="text/javascript">
    let lang = window.navigator.languages ? window.navigator.languages[0] : null;
    lang = lang || window.navigator.language || window.navigator.browserLanguage 
           || window.navigator.userLanguage;

    let shortLang = lang;
    if (shortLang.indexOf('-') !== -1)
        shortLang = shortLang.split('-')[0];

    if (shortLang.indexOf('_') !== -1)
        shortLang = shortLang.split('_')[0];

    if(shortLang === 'de')
        window.location.replace('./' + shortLang + '/index.html');
</script>

If you want to support more languages just update the if statement.

  • It does work, thanks! But since I've seen more complicated things like [here](https://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference) I was asking myself if this really is the most effective way? Don't give me wrong, I don't understand a word of the link and your code is very simple, but it seems too simple to me in comparison with other codes. Is there a difference? – Alexgamer470 Mar 02 '21 at 13:09
  • I tested my previous code in Edge, Firefox and Chrome and it worked fine. Still from the SO post you mentioned it seems like there can be differences between diffrent browsers. I updated the code. This should be working in any modern Browser now. – Till Kämmerer Mar 03 '21 at 08:53