简体   繁体   English

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

[英]Static multilanguage javascript redirection keeps reloading a page

I hope you will be able to help me with my problem.我希望你能帮助我解决我的问题。 I have 3 languages on my static html site.我的静态 html 站点上有 3 种语言。 I would like to redirect a user based on their browser language settings.我想根据用户的浏览器语言设置重定向用户。

This is my code:这是我的代码:

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

The problem is every time user will enter the website this script keeps refreshing/redirect a site.问题是每次用户进入网站时,此脚本都会刷新/重定向网站。 My question is how to check the user browser once and then redirect user to a dedicated webpage.我的问题是如何检查用户浏览器一次,然后将用户重定向到专用网页。

Thanks in advance.提前致谢。

If you don't want it to keep redirecting, you need to check for the page in the current URL.如果您不希望它继续重定向,则需要检查当前 URL 中的页面。 For example:例如:

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

This checks that the redirectURL is not in the path.这会检查redirectURL 是否不在路径中。

I think I have solved this issue using localStorage.我想我已经使用 localStorage 解决了这个问题。 Code below:代码如下:

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