Search code examples
javascriptphpcomputer-scienceuser-agent

Can you extract part of the user agent and display it?


I'm altering a bug tracking system and I have the fields for user input 'Platform','OS' and 'OS version', I want to have detection buttons which when clicked uses different 'Navigator Object Properties', this is fine and working for 'platform' and I used most if not all object properties to extract info (see below) -

<ul id="clickme">
    <li><a href="#/" id="element1" type="button" onclick="javascript:changeText(1)">Find for me</a></li>
</ul>


<div style="" id="hidden" hidden>
  <div id="demo"></div>
<script>
var txt = "";
txt += "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt += "<p>Browser Name: " + navigator.appName + "</p>";
txt += "<p>Browser Version: " + navigator.appVersion + "</p>";
txt += "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt += "<p>Browser Language: " + navigator.language + "</p>";
txt += "<p>Browser Online: " + navigator.onLine + "</p>";
txt += "<p>Platform: " + navigator.platform + "</p>";
txt += "<p>User-agent header: " + navigator.userAgent + "</p>";


document.getElementById("demo").innerHTML = txt;
</script>
</div>

You'll notice there is a button that toggles the display included.

Problem is that I cannot extract a simple answer for 'OS'and 'OS version'.

I see the desired info inside the user agent, it would be very helpful if someone knew a way to pull that info from every users 'user agent' when they are reporting a bug, is this possible?

An example of my user agent is 'User-agent header: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) (//removed browser part)

I need this bit "(Macintosh; Intel Mac OS X 10_11_1)" and would like to be able to format.

Thanks!


Solution

  • There is a neat library that helps you doing this: https://github.com/faisalman/ua-parser-js

    Example:

    <script type="text/javascript" src="ua-parser.min.js"></script>
    <script type="text/javascript">
        var parser = new UAParser();
        var os = parser.getOS();
        console.log(os.name, os.version);
    </script>