首页 > 解决方案 > 根据用户在 js 中的语言偏好重定向用户?

问题描述

很难找到任何有用的代码来运行 JavaScript 代码,将用户重定向到.html他们浏览器语言偏好的文件。所以我有一个名为的网站,index.html它是英文的。然后我在一个de/index.html德语文件夹中有另一个网站。如果他将浏览器语言偏好设置为德语,我想将用户重定向到德语网站,如果他有任何其他语言设置为他的偏好,则让他留在英语网站上。

|-index.html
|-de
  |-index.html

标签: javascripthtml

解决方案


<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 语句。


推荐阅读