In some cases, you may need to detect the browser that the user is using. This can be useful for example to show a message to the user to update their browser if it is not supported.

navigator.userAgent is a property that returns the user agent string for the current browser. This string can be used to detect the browser and its version.

Following code will detect the browser and display the name of the browser.

function getBrowserType() {
  if (navigator.userAgent.indexOf("MSIE 7") > -1) {
    return BrowserString("MSIE 7");
  }
  if (navigator.userAgent.indexOf("MSIE 8") > -1) {
    return BrowserString("MSIE 8");
  }
  if (navigator.userAgent.indexOf("MSIE 9") > -1) {
    return BrowserString("MSIE 9");
  }
  if (navigator.userAgent.indexOf("MSIE 10") > -1) {
    return BrowserString("MSIE 10");
  }
  if (navigator.userAgent.indexOf("rv:11.0") > -1) {
    return BrowserString("rv:11.0");
  }
  if (navigator.userAgent.indexOf("Firefox") > -1) {
    return BrowserString("Firefox");
  }
  if (navigator.userAgent.indexOf("Chrome") > -1) {
    return BrowserString("Chrome");
  }
  if (navigator.userAgent.indexOf("Opera") > -1) {
    return BrowserString("Opera");
  } else {
    return "Unknown";
  }
}

Here are the properties of navigator.userAgent

PropertyDescription
navigator.userAgentReturns the user agent string for the current browser.
navigator.appNameReturns the name of the browser.
navigator.appVersionReturns the version information of the browser.
navigator.platformReturns for which platform the browser is compiled.
navigator.cookieEnabledReturns whether cookies are enabled in the browser.
navigator.javaEnabled()Returns whether Java is enabled in the browser.
navigator.onLineReturns whether the browser is online.
navigator.languageReturns the language of the browser.
navigator.userLanguageReturns the language of the browser.
navigator.systemLanguageReturns the operating system language.
navigator.productReturns the engine name of the browser.
navigator.productSubReturns the engine version of the browser.
navigator.vendorReturns the vendor name of the browser.
navigator.vendorSubReturns the vendor version of the browser.
navigator.appCodeNameReturns the code name of the browser.
navigator.appMinorVersionReturns the minor version information of the browser.
navigator.mimeTypesReturns an array of all the MIME types supported by the browser.

Why not to use JS browser detection?

JS browser detection is not a good practice. It is better to use feature detection instead of browser detection. Its better because it is more reliable and it is more future proof. AlsoJS based browser detection can be spoofed by the user.


Reference: