How to Get User Agent in JavaScript

  1. What is a User Agent
  2. Get User Agent in JavaScript
How to Get User Agent in JavaScript

This article will explain the purpose of agents and let you know how it works in JavaScript source code. We will also check how we can get a user agent in the JavaScript program.

What is a User Agent

A user agent is a property of a navigator. During a URL request from the browser to the server, our browser sends its user agent to the website we are interacting with.

The user agent is a string or line containing the browser and operating system identification.

A user agent field is included in HTTP request headers, and that agent field content may vary from browser to browser. Each browser has its specific user agent.

This information can be helpful for web servers to manage these services to serve different web pages to different web browsers or operating systems.

For example, a web server could send the mobile webpage to a mobile browser or an advanced web page to an advanced web browser. And web server can also recommend users update their browser.

Here is an example of user agent content.

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19041

Get User Agent in JavaScript

In JavaScript, we can create a custom function to get the active browser agents’ content. With the help of the navigator property userAgent, we can find the agent content field, and that property is read-only.

Example in JavaScript:

<html>
    <head>
        <title>get agent in JavaScript</title>
    </head>
    <script>
    function getAgent()
    {
        let agent = navigator.userAgent; //get agent from navigator property
        document.getElementById("agent").innerHTML = "User-agent:<br>" + agent;
    }
    </script>
    <body>

        <h1 style="color:blueviolet">DelftStack Learning</h1>
        <h3>JavaScript Get Agent</h3>

        <p>Click on button to get the agent</p>

        <button onclick="getAgent()">Click me</button>

        <p id="agent"></p>
    </body>
</html>

Output:

Get User Agent in JavaScript

As shown in the above source code, we declared a let type function getAgent() in <script></script> tags which will be triggered by a button click event.

Inside that function, we have to get user agent content by using navigator property navigator.userAgent and store that string value to a variable. Then, we have assigned that variable to the paragraph element using HTML document default method getElementById("agent").innerHTML.

We have created the button element Click me and called the getAgent() function on the click event to display agent content on the web page.

You can save the above source with the extension of HTML and open it in the browser to see the result.