静态多语言JavaScript重定向会不断重新加载页面

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

每当用户进入网站时,此脚本都会不断刷新/重定向一个站点。我的问题是如何检查用户浏览器一次,然后将用户重定向到专用网页。
提前致谢。
2个回答

2

如果您不希望它继续重定向,您需要检查当前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;
}

这个检查确保重定向URL不在路径中。


感谢您的回答。所有文件都在根目录中,上面的代码正在检查用户浏览器语言,并基于该信息重定向到特定页面。一旦用户被重定向,脚本会再次检查用户语言(无限循环)。也许我应该在第一次重定向后添加一些内容到URL中,或者使用localstorage? - Kamil
如果您想存储选项是什么,可以使用localstorage或cookies,但实际上您不需要这样做。如果仍然重定向,则说明路径检查存在问题。请注释掉document.location.href并输出(alert或console.log)它所显示的内容。例如:alert(document.location.path+" != /"+redirectURL) - fanfavorite
返回 Undefinded != /index_pl.html但是所有文件都在同一个根目录中。 - Kamil
抱歉,是我的错。应该是文件路径名。请参见上面的修订。 - fanfavorite
这可能在服务器上可以工作,但在本地主机上会返回 E:/filelocation/foldername/index.html != /index_pl.html。我想我必须找到其他解决方案... - Kamil
你可以检查window.location.pathname.indexOf(redirectURL) > -1。 - fanfavorite

0

我认为我已经通过使用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());

这个解决方案的问题在于你在重定向之后设置了日期。我仍然认为你不需要它。你可以看到我的修改后的解决方案,用于检查字符串中的 redirectURL 的实例,这样它就可以在本地主机上工作。这种方法也可以,但你需要在重定向之前设置项目。你可以把它放在 if 语句的第一个项目里。 - fanfavorite

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接