javascript - 根据用户在 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 语句。
推荐阅读
- javascript - React Native 上的 XSLT 处理器(从 XML 到 HTML)
- javascript - 检查选择器的 innerText 是否包含子字符串
- nestjs - NestJS + 类验证器,为什么错误数组是空的?
- postgresql - 从postgresql 10中的日期列生成的列
- docker - 尝试下载图像时,Kitematic 卡在连接到 Docker 集线器
- java - Android图像意图不显示图像
- c# - MemoryStream 可以减少它的容量吗?
- python - 为什么分别使用requests和aiohttp会得到不同的结果?
- ios - CocoaPods 停止安装 Firebase/Analytics 并出现错误
- r - 按条件合并两个 CSV