Quantcast
Channel: MSDN Blogs
Viewing all articles
Browse latest Browse all 12366

Detecting browser language using JavaScript

$
0
0

 

I was recently working on helping someone localize their ADFS 3.0 login page. They had changed the theme and had some custom text like their organization name and some instructions to login. The challenge was localizing this custom text when people from a different country say France with their language set as French (FR) tries to access the site.\

Maybe there are better ways to this is ADFS. I am no ADFS expert but I was told that you got to use it using the exported OnLoad JavaScript method. So I thought of writing something in JavaScript to help identify the default language. I initially tried to use the navigator to get the language

var language = window.navigator.userLanguage || window.navigator.language;
alert(language);

Soon I understood that this wont work since its returning the language of the browser itself as in if you installed English version of Chrome, it would return EN. This is not what I wanted. So what I had to do was extract it from the Request Header. The header would look something like this:

Connection: Keep-Alive
Accept: text/html, application/xhtml+xml, image/jxr, */*
Accept-Encoding: gzip, deflate, peerdist
Accept-Language: fr-FR, fr; q=0.8, en-US; q=0.5, en; q=0.3
Cookie: glimpsePolicy=On; shopper=7cc14a57-c195-498b-b8f8-825d61434119
Host: localhost:57350
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
DNT: 1
X-P2P-PeerDist: Version=1.1
X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0

The highlighted header is what we are interested in. Since we can get this from the JavaScript, I wrote a simple Web API and hosted in Azure.

public class LanguageController : ApiController
    {
        // GET api/Language
        public IEnumerable<string> Get()
        {
            return Request.Headers.AcceptLanguage.ToList().Select(lang => lang.Value).ToList();
        }
    }

This API is hosted in http://detectbrowserlanguage.azurewebsites.net/api/language and as you can see it returns an array of all accepted languages. The rest is simple CSS and JQuery to do the trick. One other thing was I could not have references the JQuery using script tags so I ended up adding JQuery through my JavaScript itself. Looks something like this:

<html>
<head>
<style>
   p {
    display: none;
   }
   body:lang(en) p:lang(en) {
    display : inline;
   }
   body:lang(cz) p:lang(cz) {
    display : inline;
   }
   body:lang(en-US) p:lang(en-US) {
    display : inline;
   }
</style>
<script>
 
    function loadScript(url, callback) {

        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { //Others
            script.onload = function () {
                callback();
            };
        }

        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

    loadScript("http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js", function () {       
         // Send an AJAX request
        $.getJSON("
http://detectbrowserlanguage.azurewebsites.net/api/language")
         .done(function (data) {
            // On success, 'data' contains a list of products.
            if(data && data.length>0){
                $('body').prop("lang",data[0]);
            }
           
            $.each(data, function (index,language) {
              // Add a list item for the product.                           
              //$('body').prop("lang",language);
            });
        });
    });
</script>
</head>
<body class="cz">   
   <div>
     <p lang="en">Hello</p>
     <p lang="cz">Ahoj</p>
     <p lang="ru">Privet</p>
   </div>
</body>
</html>

This loads the appropriate greeting text to match the default language of the end user. Of course this does not support all languages but you get the point.

Hope this helps if you are trying to get something similar done.


Viewing all articles
Browse latest Browse all 12366

Trending Articles