Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect user to different page?

I need to make to redirect the user to another page, in accordance to the language of the browser. For example: if the language of the browser english redirect to site.com/en/.

I try to do like this:

$(document).ready(function () {
    var userLang = navigator.language || navigator.userLanguage;

    switch (userLang) {
        case 'en':
            window.location.href = window.location.origin + '/en';
            break;
        case 'de':
            window.location.href = window.location.origin + '/de';
            break;
        default:
            break;
    }
});

It's works but the page is constantly reloaded. How to solve it or prompt another solution?

like image 696
Ihor Tkachuk Avatar asked Sep 27 '22 13:09

Ihor Tkachuk


1 Answers

The page is constantly reloaded as you're not checking whether the user is already on the correct language site.

On your pages you could store a javascript variable for the pages language produced server-side. For example:

var thisLanguage = 'en';

Then change your javascript logic to take this into account and only apply the redirect if the user's language is different to thisLanguage:

$(document).ready(function () {
    var userLang = navigator.language || navigator.userLanguage;

    if (userLang != thisLanguage){

       switch (userLang) {
           case 'en':
               window.location.href = window.location.origin + '/en';
               break;
           case 'de':
               window.location.href = window.location.origin + '/de';
               break;
           default:
               break;
       }

    }
});
like image 159
Curtis Avatar answered Oct 03 '22 23:10

Curtis