Identify browser using userAgent

I have been trying to figure out about the information that server gets. One of things the server can know is the browser version (also the manufacturer).

The below code is for client side JavaScript but with minor tweaks, you can use it on the server too.

 * Extracts the browser name and version number from user agent string.
 * @param userAgent
 *            The user agent string to parse. If not specified, the contents of
 *            navigator.userAgent are parsed.
 * @param elements
 *            How many elements of the version number should be returned. A
 *            value of 0 means the whole version. If not specified, defaults to
 *            2 (major and minor release number).
 * @return A string containing the browser name and version number, or null if
 *         the user agent string is unknown.
function identifyBrowser(userAgent, elements) {
  var regexps = {
      Chrome: [/Chrome\/(\S+)/],
      Firefox: [/Firefox\/(\S+)/],
      MSIE: [/MSIE (\S+);/],
      Opera: [
        /Opera\/.*?Version\/(\S+)/ /* Opera 10 */,
        /Opera\/(\S+)/ /* Opera 9 and older */,
      Safari: [/Version\/(\S+).*?Safari\//],

  if (userAgent === undefined) userAgent = navigator.userAgent;

  if (elements === undefined) elements = 2;
  else if (elements === 0) elements = 1337;

  for (browser in regexps)
    while ((re = regexps[browser].shift()))
      if ((m = userAgent.match(re))) {
        version = m[1].match(
          new RegExp('[^.]+(?:.[^.]+){0,' + --elements + '}'),
        return browser + ' ' + version;

  return null;

In NodeJS, you can get user agent string using the request object.


Frequently asked questions

Will this code work on python?

Yeah, if you could transpile it into python you can make it work

OK, how can I get the User Agent String on the Server

The user agent will be in the headers of the request object on the server. See the tip above for example in NodeJS.

Last Updated on

Next Post: GraphProtocol: TS2322 null assignment in Subgraph →