by Peter Moss
28. February 2010 05:50
Times of detecting a version number of a web browser hitting your site are probably behind us. However, there are still differences in DOM behaviour among leading browser implementations, especially when it comes to DOM event handling.
Folks at Redmond and other places still cannot agree on programming syntax of DOM event processing.
For this and any other scenarios where you need to code your Javascript for a particular browser type, you need to detect the browser type.
This is done by checking a user agent header. Fortunately, we’ve got a navigator object that is available in all major browsers.
Here is an example of Javascript code that can be used to detect a browser type.
<script type="text/javascript">
// -----------------------------------------------------
// Copyright © 2006 Peter Moss, All Rights Reserved.
// Author: Peter Moss, P. Eng., http://www.petermoss.com
// This source code can be used in any derived work
// provided that the above copyright notice is shown.
// -----------------------------------------------------
// -------------------------
// Get a browser identifier.
// -------------------------
function getBrowserID()
{
var ua = navigator.userAgent.toLowerCase();
if (/opera/.test(ua)) return 'opera';
if (/msie/.test(ua)) return 'msie';
if (/(khtml|webkit)/.test(ua)) return 'webkit';
if ( /mozilla/.test(ua) &&
!/(webkit|compatible)/.test(ua)
)
return 'mozilla';
return 'other';
} // end of getBrowserID()
// Now you can use bID variable anywhere in your
// Javascript code.
var bID = getBrowserID();
</script>
Download: browserid.js
Once the browser type is determined, one can code DOM event initialization and event handling routines accordingly.