简体   繁体   中英

How can I detect the user's language and redirect to a language appropriate webpage?

I'm trying to detect the user's language settings, then redirect her based on that. If the user has pl as her default language setting, she should be redirected to polish.html . If ru , then russian.html . Otherwise, english.html .

a = navigator.language;
b = navigator.userLanguage;

language = (a && !b)? a.toLowerCase() : b;

pl = 'pl';
ru = 'ru';
en = 'en'||'us'||'au'||'bz'||'ca'||'gb'||'ie'||'jm'||'nz'||'tt'||'za';

switch (language) {
  case pl: window.location.replace('polish.html'); break;
  case ru: window.location.replace('russian.html'); break;
  case en: window.location.replace('english.html'); break;
}

In general, the above script works, except for one problem: the browser continually refreshes the page. How can I fix this problem?

Your problem is that you are continually reloading the page, regardless of your current state. If your user's language is English and you're on english.html , there's no reason to reload the page.

var language = (navigator.language || navigator.userLanguage).toLowerCase(),
    // simpler way of getting the user's language (take advantage of || in JS)
    en = [ "en", "us", "au", "bz", "ca", "gb", "ie", "jm", "nz", "tt", "za" ],
    // we'll need an array of the languages associated with English
    currentPage = window.location.href.toLowerCase();

if (language == "pl" && currentPage.indexOf("polish") == -1) {
    // if the user's language is polish and the page's link doesn't contain polish
    // in it, redirect the user to polish.html
    window.location.replace("polish.html");
} else if (language == "ru" && currentPage.indexOf("russian") == -1) {
    // same concept as above
    window.location.replace("russian.html");
} else if (en.indexOf(language) > -1 && currentPage.indexOf("english") == -1) {
    // here, we're checking whether their language is in the array
    // of user languages that should default to english
    window.location.replace("english.html");
}

You can even simplify the above logic by removing en.indexOf(language) > -1 from the last else if statement. This'll make the default landing page english.html .

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