Saturday, March 31, 2012

Detect Browsers using jQuery

jQuery provides a property to detect the browser. It works well for IE, mozilla, Safari and opera browser but it doesn't work for Google Chrome. Below jQuery code gives you an idea about $.browser property



$(document).ready(function() {
  if ($.browser.mozilla && $.browser.version >= "2.0" ){
   alert('Mozilla above 1.9');
  }
  
  if( $.browser.safari ){
   alert('Safari');
  }
 
  if( $.browser.opera){
   alert('Opera');
  }
 
  if ($.browser.msie && $.browser.version <= 6 ){
   alert('IE 6 or below version');
  }
 
  if ($.browser.msie && $.browser.version > 6){
   alert('IE above 6');
  }
});





The jQuery browser property allows you to determine the browser in which the webpage is running. This property makes use of navigator.userAgent to determine the platform. As said earlier, that this property doesn't work for Chrome. If you simply make an alert statement of navigator.userAgent in chrome then you will see Chrome and Safari both the words in alert statement.
Then how to detect chrome?

Well, if you have installed chrome on your machine and safari is not installed then you can use $.browser.safari to detect chrome. As both the browsers are fully based on webkit. webkit is one of the flag of $.browser property. It will be true for safari and chrome. But that's not a proper way to detect chrome.

Well, you need to alter the $.browser utility to support chrome. I found a good article about detecting chrome using jQuery. Visit here.

No comments: