Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User Agent parsing in Javascript

I need to extract the Operating System's name and the browser's name from the user agent string.

Sample of user agent:

Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.9) Gecko/20100825 Ubuntu/9.10 (karmic) Firefox/3.6.9

How can I get just the operating system (example "Linux i686" and "Firefox 3.6.9")?

Here is my codes in fiddle link which is as follows:

function getBrowserAndOS(userAgent, elements) {
  var browserList = {
      'Chrome': [/Chrome\/(\S+)/],
      'Firefox': [/Firefox\/(\S+)/],
      'MSIE': [/MSIE (\S+);/],
      'Opera': [
        /Opera\/.*?Version\/(\S+)/,
        /Opera\/(\S+)/
      ],
      'Safari': [/Version\/(\S+).*?Safari\//]
    },
    re, m, browser, version;


  var osList = {
      'Windows': [/Windows\/(\S+)/],
      'Linux': [/Linux\/(\S+)/]
    },
    re2, m2, os;

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

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

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


  for (os in osList) {
    while (re2 = osList[os].shift()) {
      if (m2 = userAgent.match(re2)) {
        //version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,' + --elements + '}')))[0];
        //version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,}')))[0];
        //return browser + ' ' + version;
        console.log(os);
      }

    }
  }

  return null;
}

console.log(getBrowserAndOS(navigator.userAgent, 2));

I just need to extract the OS name and the browser name with their respective versions. How can I parse it to get those string?

like image 567
jeewan Avatar asked Jul 19 '26 00:07

jeewan


1 Answers

I wouldn't recommend doing this yourself. I'd use a parser like Platform.js, which works like this:

<script src="platform.js"></script>
<script>
var os = platform.os;
var browser = platform.name + ' ' + platform.version;
</script>
like image 188
Evan Hahn Avatar answered Jul 20 '26 14:07

Evan Hahn