While you ideally shouldn’t use browser detection to choose whether or not to render something in a particular fashion, jQuery does provide the capability to work out which browser rendering engine and version is being used with $.browser. There is also $.support which provides information about what the rendering engine supports and I will look at that in a later post.
Working example
A piece of Javascript directly after this paragraph will show the browser flags that jQuery detects and the version. If you are reading this in a feed reader then this will not work and you will need to click through to read this article in a web browser.
Warning: $.browser is deprecated
The $.browser property was deprecated in jQuery 1.3 but there are no immediate plans to remove it from jQuery. As I noted in the first paragraph, ideally it shouldn’t be used anyway but there may be times for debugging or logging that it may be useful to record this information.
$.each($.browser, function(key, val) {
document.write(key + " : " + val + "
");
});
$.browser properties
jQuery’s $.browser has several true/false flags which indicate which browser engine is being used. These can be tested in conditional statements or the values dispayed in an each loop.
The available flags are:
- mozilla
- msie
- opera
- safari
- webkit (added in jQuery 1.4)
For jQuery versions < 1.4 Chrome and Safari are flagged as safari; in jQuery 1.4 they are both flagged as both safari and webkit. In future versions they will presumably instead only be flagged as webkit.
There is also a "version" property which reports the rendering engine’s version number. This is not the same as the browser’s version number. For example, for Chrome version 4.0.249.78 $.browser.version will be 532.5; for Firefox 3.5.7 $.browser.version will be 1.9.1.7
Using $.browser in a conditional
The following example does one thing or another depending on the flag that is set:
if($.browser.webkit) { // do something } else if($.browser.safari) { // do something } else if($.browser.opera) { // do something } else if($.browser.msie) { // do something } else if($.browser.mozilla) { // do something }
Using $.browser with $.each
To loop through all the properties in $.browser do the following:
$.each($.browser, function(key, val) { document.write(key + " : " + val + "<br />"); });
This is what is done in the working example at the start of this post. Instead of writing it to the document the information could be put into a string and sent along with an AJAX request etc.