简体   繁体   中英

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?

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.

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