简体   繁体   中英

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. 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. 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.

I think I have solved this issue using 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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