Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

Faraz

By Faraz -

Learn how to detect user's browser, OS, and screen resolution with UAParser.js. Optimize your web development and deliver a tailored user experience.


Detecting User OS and Screen Resolution with JavaScript and UAParser.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

User agent parsing is a fundamental aspect of web development. It involves extracting information about a user's browser, operating system, and device to optimize the web experience. In this blog post, we'll delve into how to achieve this using HTML, CSS, JavaScript, and the UAParser.js library.

Join My Telegram Channel to Download the Project Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down the code step by step:

1. <!DOCTYPE html>: This declaration specifies that the document is written in HTML5, the latest version of HTML.

2. <html lang="en">: This tag defines the start of the HTML document and sets the document's primary language to English.

3. <head>: The head section contains meta-information and external resources that aren't visible on the web page itself but are used to configure and provide information about the page.

  • <meta charset="UTF-8">: This meta tag specifies the character encoding of the document, which is UTF-8, a widely used character encoding that supports various languages and special characters.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is typically used to specify how Internet Explorer should render the webpage. In this case, it sets IE to use the latest available rendering engine.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is often used for responsive web design. It ensures that the web page adjusts its content to fit the width of the device's screen and sets the initial zoom scale to 1.0.
  • <title>Detect user's browser, screen resolution</title>: This title tag sets the title of the web page that appears in the browser's tab or window. The title is "Detect user's browser, screen resolution" in this case.
  • <link rel="stylesheet" href="styles.css">: This link tag references an external CSS (Cascading Style Sheets) file named "styles.css" to apply styles to the web page's content.

4. <body>: The body section contains the visible content of the web page.

  • <h2>Detect user agent, browser, os, screen resolution, and other debug info</h2>: This is a level 2 (h2) heading that provides a title for the web page, describing the purpose of the page.
  • <p><i>An easy method using UA-Parser (https://github.com/faisalman/ua-parser-js) and vanilla JavaScript variables to detect user info for debugging, such as browser version, os, screen resolution, device type, etc.</i></p>: This is a paragraph (p) containing italicized text that describes the purpose of the page and mentions the use of "UA-Parser" and JavaScript for detecting user information.
  • <div id="debug-container"></div>: This is an empty div element with the id "debug-container." This div will be used to display the detected user information.
  • <button class="refresh-button" onclick="getDebugInfo()">Refresh </button>: This is a button element with the class "refresh-button." It has an onclick attribute that calls a JavaScript function named "getDebugInfo()" when clicked. This function will presumably trigger the detection and display of user information.
  • <script src='https://cdnjs.cloudflare.com/ajax/libs/UAParser.js/0.7.12/ua-parser.min.js'></script>: This script tag references an external JavaScript library called "ua-parser.min.js" from a Content Delivery Network (CDN). This library is used for parsing and extracting user agent information from the browser.
  • <script src="script.js"></script>: This script tag references an external JavaScript file named "script.js," which is used to handle the detection and display of user information on the web page.

This is the basic structure using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the website is in place, the next step is to add styling to the tools using CSS.

Next, we will create our CSS file. Let me explain each part of the code:

1. body: This part of the code applies styles to the entire web page's body element.

  • background: #d4fddf; sets the background color of the webpage to a light green color (#d4fddf).
  • font-family: Arial; sets the font for the text within the body to Arial.
  • margin: 30px; adds a 30-pixel margin around the body of the webpage.

2. #debug-container: This code applies styles to an element with the ID "debug-container." It might be a container for debugging information or a specific section of the webpage.

  • max-width: 400px; restricts the maximum width of the container to 400 pixels.
  • border: 3px solid orange; adds a 3-pixel wide solid orange border around the container.
  • padding: 20px; provides 20 pixels of padding inside the container.
  • margin-bottom: 10px; creates a 10-pixel margin at the bottom of the container.

3. .debug-info: This code applies styles to elements with the class "debug-info." It seems like this class is used to style debugging information within the container.

  • display: flex; sets the display property to "flex," which allows for flexible layout options.
  • justify-content: space-between; positions the contents of the container so that there is space between them, pushing them to the left and right edges of the container.
  • margin: 10px; adds a 10-pixel margin around each element with this class.
  • font-size: 20px; sets the font size to 20 pixels for text within elements with this class.

4. .refresh-button: This code applies styles to elements with the class "refresh-button." This class is used to style buttons or elements that trigger a refresh action.

  • padding: 10px; provides 10 pixels of padding inside the button element.
  • background: orange; sets the background color of the button to orange.
  • border: 1px solid black; adds a 1-pixel wide solid black border around the button.
  • font-family: inherit; inherits the font-family from the parent element.
  • font-size: 18px; sets the font size to 18 pixels for text within elements with this class.

Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  background: #d4fddf;
  font-family: Arial;
  margin: 30px;
}

#debug-container {
  max-width: 400px;
  border: 3px solid orange;
  padding: 20px;
  margin-bottom: 10px;
}

.debug-info {
  display: flex;
  justify-content: space-between;
  margin: 10px;
  font-size: 20px;
}

.refresh-button {
  padding: 10px;
  background: orange;
  border: 1px solid black;
  font-family: inherit;
  font-size: 18px;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let's break down the code step by step:

1. getDebugInfo() Function:

  • This function is defined to collect and display various pieces of information about the user's operating system, browser, device, screen, and more. It uses the UAParser library to extract some of this information.

2. Variable Declarations:

  • infoSections: An empty array that will be used to store sections of information.
  • parser: An instance of the UAParser class, which is used to parse user agent strings and extract information about the user's browser and operating system.
  • userOs, userDevice, and userBrowser: These variables are used to store information about the user's operating system, device, and browser, respectively, by calling methods on the parser object.
  • debugContainer: It is used to obtain a reference to an HTML element with the ID "debug-container" in the document.

3. Collecting Information:

  • The code checks if information about the operating system, browser, and device is available and pushes this information as objects into the infoSections array.

4. Screen and Window Information:

  • The code also collects information about the user's screen resolution, available screen space, browser window size, and device pixel ratio, and adds this information to the infoSections array.

5. Clearing Existing Debug Information:

  • The code clears any existing child nodes of the element with the ID "debug-container."

6. Rendering Debug Information:

  • A loop iterates through the infoSections array and creates HTML elements to display the information. These elements are added as child nodes to the "debug-container" element.

7. Event Listeners:

  • Two event listeners are set up. One listens for the "resize" event, and the other listens for the "orientationchange" event on the window object. When these events are triggered, the getDebugInfo() function is called, updating and re-rendering the debug information.

8. Initial Invocation:

  • Finally, the getDebugInfo() function is initially called to display the debug information when the page loads.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

function getDebugInfo() {
  var infoSections = [];
  var parser = new UAParser();
  var userOs = parser.getOS();
  var userDevice = parser.getDevice();
  var userBrowser = parser.getBrowser();
  var debugContainer = document.getElementById("debug-container");

  if (userOs && userOs.name && userOs.version) {
    infoSections.push({ name: 'OS', value: userOs.name + ' ' + userOs.version});
  }

  if (userBrowser && userBrowser.name && userBrowser.version) {
    infoSections.push({ name: 'Browser', value: userBrowser.name + ' ' + userBrowser.version});
  }

  if (userDevice && userDevice.vendor && userDevice.model) {
    infoSections.push({ name: 'Device', value: userBrowser.vendor + ' ' + userBrowser.model});
  } else {
    infoSections.push({ name: 'Device', value: 'N/A'});
  }

  if (window) {
    if (window.screen) {
      infoSections.push({ name: 'Screen resolution', value: window.screen.width + 'x' + window.screen.height});
      infoSections.push({ name: 'Available screen space', value: window.screen.availWidth + 'x' + window.screen.availHeight});
    }

    infoSections.push({ name: 'Browser window size', value: window.innerWidth + 'x' + window.innerHeight});
    infoSections.push({ name: 'Device pixel ratio', value: window.devicePixelRatio });
  }

  while (debugContainer.hasChildNodes()) {
    debugContainer.removeChild(debugContainer.lastChild);
  }

  for (var i = 0; i < infoSections.length; i++) {
    var debugInfo = document.createElement("div");
    debugInfo.setAttribute("class", "debug-info");
    var debugName = document.createElement("div");
    debugName.setAttribute("class", "debug-name");
    debugName.appendChild(document.createTextNode(infoSections[i].name));
    var debugValue = document.createElement("div");
    debugValue.setAttribute("class", "debug-value");
    debugValue.appendChild(document.createTextNode(infoSections[i].value)); 
    debugInfo.appendChild(debugName);
    debugInfo.appendChild(debugValue);
    debugContainer.appendChild(debugInfo);
  }
}

window.addEventListener("resize", function () {
  getDebugInfo();
}, false);

window.addEventListener("orientationchange", function () {
  getDebugInfo();
}, false);

getDebugInfo();

Final Output:

Detecting User OS and Screen Resolution with JavaScript and UAParser.gif

Conclusion:

In conclusion, user agent parsing is crucial for creating a dynamic and user-centric web experience. UAParser.js simplifies the process of detecting the user's browser, OS, and screen resolution, allowing you to craft responsive designs and deliver personalized content. Explore other JavaScript libraries for additional functionality and stay ahead in the world of web development.

Code by: Martin

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post