Thursday, March 1, 2018

detect browser language and redirect using javascript

When first time user open the site and detect browser language and redirect website according to languge using javascript.

 <script>
function GetCookie(name) {
        var arg=name+"=";
        var alen=arg.length;
        var clen=document.cookie.length;
        var i=0;

        while (i<clen) {
            var j=i+alen;
                if (document.cookie.substring(i,j)==arg)
                    return "here";
                i=document.cookie.indexOf(" ",i)+1;
                if (i==0)
                    break;
        }

        return null;
    }
$(function getck() {
    var visit=GetCookie("COOKIE1");
    if (visit==null){
        var userLang = navigator.language || navigator.userLanguage;
if(userLang=="fr"){
window.location='http://french.domain.com/';
}else if(userLang=="en-US"){
window.location='http://english.domain.com/';
}else{
window.location='http://domain.com/';
}
    }
    var expire=new Date();
    expire.setTime(expire.getTime()+(1*24*60*60*1000));
    document.cookie="COOKIE1=here; expires="+expire;
});
</script>

No comments:

Post a Comment