静态多语言javascript重定向保持重新加载页面

Static multilanguage javascript redirection keeps reloading a page

本文关键字:加载 新加载 语言 javascript 重定向 静态      更新时间:2023-09-26

我希望你能帮我解决这个问题。我有3种语言在我的静态html网站。我想根据用户的浏览器语言设置重定向用户。

这是我的代码:

    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());