Tuesday, September 16, 2014

Detect the browser through javascript

In Cordys we do have a simple "system" variable which tells which browser we are using like below

system.isIE
system.isChrome

etc.,

But here the dependency would be system variable would be defined in a javascript in "application.js" which is a cordys platform javascript file.

To remove this dependency the following can be done

navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem, 
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\bOPR\/(\d+)/)
        if(tem!= null) return 'Opera '+tem[1];
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

And you can use this piece of code like below

if(!navigator.sayswho.toLowerCase().indexOf("ie "))
 {
 charCode = (event.which) ? event.which : event.keyCode;
 windowEventCode = event;
 }else if (window.event)
 {
  charCode = window.event.keyCode;
  windowEventCode = window.event;
 }


No comments:

Post a Comment