javascriptjqueryloopshttp-redirectuserlocation

Endless redirect loop when trying to redirect user to /en with navigator.language


I've got a German Wordpress website (http://website.de) and made an English version of every page with TranslatePress (http://website.de/en). Now I tried to get the language of every user in JQuery with navigator.language and redirect not German-speaking users to /en:

<script type="text/javascript">
    $(document).ready(function(){
        var userLang = navigator.language || navigator.userLanguage;
        if (userLang == "de") {
            window.location = "http://www.website.de";;
        }
        else {
            window.location = "http://www.website.de/en";
        }
    });
</script>

But it results in an endless loop and the page is reloading every second. What can I do to avoid this?


Solution

  • Robin Zigmond is correct - if you redirect in both the if and the else block, it will always result in an infinite loop (save for an exception). Maybe try

     <script type="text/javascript">
            $(document).ready(function(){
                var userLang = navigator.language || navigator.userLanguage;
                var isUserOnEnglishVer = window.location.href.indexOf("website.de/en") >=0;
                if (userLang == "de" && isUserOnEnglishVer) {
                    window.location = "http://www.website.de";
                }
                if (userLang != "de" && !isUserOnEnglishVer){
                    window.location = "http://www.website.de/en";
                }
            });
        </script>
    

    In other words, only redirect if you aren't on the correct version.

    However, I would find it surprising if there isn't an in-built way for language redirects.