繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM