[英]redirect user based on their language preference in js?
很难找到任何有用的代码来运行 JavaScript 代码,它将用户重定向到他们浏览器语言首选项的.html
文件。 所以我有一个名为index.html
的网站,它是英文的。 然后我在文件夹de/index.html
中有另一个网站,它是德语的。 如果他将浏览器语言偏好设置为德语,我想将用户重定向到德语网站,如果他有任何其他语言设置为他的偏好,则让他留在英语网站上。
|-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 语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.