简体   繁体   English

根据用户在 js 中的语言偏好重定向用户?

[英]redirect user based on their language preference in js?

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.很难找到任何有用的代码来运行 JavaScript 代码,它将用户重定向到他们浏览器语言首选项的.html文件。 So I have a website which is named index.html and it is in english.所以我有一个名为index.html的网站,它是英文的。 And then I have another website in a folder de/index.html which is in german.然后我在文件夹de/index.html中有另一个网站,它是德语的。 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
<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.如果您想支持更多语言,只需更新 if 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM