Posted By

merrittwjm on 05/07/11


Tagged

javascript js browser detection


Versions (?)

Browser Detection


 / Published in: JavaScript
 

  1. /* getBrowser Extracts the browser name and version number from user agent string.
  2. * @param elements -
  3. * How many elements of the version number should be returned. A
  4. * value of 0 means the whole version. If not specified, defaults to
  5. * 2 (major and minor release number).
  6. */
  7. function getBrowser(elements) {
  8. var userAgent = navigator.userAgent;
  9. var regexps = {
  10. 'Chrome': [ /Chrome\/(\S+)/ ],
  11. 'Firefox': [ /Firefox\/(\S+)/ ],
  12. 'MSIE': [ /MSIE (\S+);/ ],
  13. 'Opera': [ /Opera\/.*?Version\/(\S+)/, /* Opera 10 */
  14. /Opera\/(\S+)/ ], /* Opera 9 and older */
  15. 'Safari': [ /Version\/(\S+).*?Safari\// ]
  16. },
  17. re, m, browser, version;
  18.  
  19. if (elements === undefined)
  20. {
  21. elements = 2;
  22. }
  23. else if (elements === 0)
  24. {
  25. elements = 1337;
  26. }
  27.  
  28. for (browser in regexps)
  29. {
  30. while (re = regexps[browser].shift())
  31. {
  32. if (m = userAgent.match(re))
  33. {
  34. version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,' + --elements + '}')))[0];
  35. browserObj = { name : browser, version : version }
  36. return browserObj;
  37. }
  38. }
  39. }
  40. return null;
  41. }

Report this snippet  

You need to login to post a comment.