[英]Static multilanguage javascript redirection keeps reloading a page
我希望你能幫助我解決我的問題。 我的靜態 html 站點上有 3 種語言。 我想根據用戶的瀏覽器語言設置重定向用戶。
這是我的代碼:
var lang = navigator.language;
if (lang == 'pl'){
document.location.href = 'index_pl.html';
}
else if (lang == 'fr'){
document.location.href = 'index_fr.html';
}
else {
document.location.href = 'index.html';
}
alert(lang);
問題是每次用戶進入網站時,此腳本都會刷新/重定向網站。 我的問題是如何檢查用戶瀏覽器一次,然后將用戶重定向到專用網頁。
提前致謝。
如果您不希望它繼續重定向,則需要檢查當前 URL 中的頁面。 例如:
var lang = navigator.language;
var redirectURL = 'index.html';
if (lang == 'pl'){
redirectURL = 'index_pl.html';
} else if (lang == 'fr'){
redirectURL = 'index.html';
}
if (document.location.pathname.indexOf(redirectURL) == -1) {
document.location.href = redirectURL;
}
這會檢查redirectURL 是否不在路徑中。
我想我已經使用 localStorage 解決了這個問題。 代碼如下:
if (localStorage.getItem("visit") == null)
{
// Show Welcome message
var lang = navigator.language;
if (lang == 'pl'){
document.location.href = 'index_pl.html';
}
else if (lang == 'fr'){
document.location.href = 'index_fr.html';
}
else {
document.location.href = 'index.html';
}
}
localStorage.setItem("visit", new Date());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.