JavaScript Get Browser Name and Version

JavaScript Get Browser Name and Version
Code Snippet:JavaScript | Detect Browser
Author: Stefan Natter
Published: January 18, 2024
Last Updated: January 22, 2024
Downloads: 712
License: MIT
Edit Code online: View on CodePen
Read More

If you’re wondering how to detect the browser name and version using JavaScript, you’ve come to the right place. This code provides valuable insights into your user’s browser and device.

This code helps you gain insights into your users’ devices and browsers, which can be useful for tailoring your web applications accordingly. It helps you tailor your web content and features for a better user experience. Moreover, it also supports compatibility checks for Chrome and Firefox, ensuring a smoother browsing experience.

How to Get the Browser Name And Version Using JavaScript

1. First, create an HTML file for your project. Inside the <body> tag, add the following code:

<div class="max-w-lg my-0 mx-auto">
  <h1 class="text-2xl mb-4 underline">Detect Browser</h1>

  <div class="result">
    <h2 class="text-1xl my-4 italic underline">Navigator</h2>
    <p class="my-1"><span class="font-bold">userAgent:</span> <span id="useragent">-</span></p>
    <p class="my-1"><span class="font-bold">appVersion:</span> <span id="appVersion">-</span></p>
    <p class="my-1"><span class="font-bold">platform:</span> <span id="platform">-</span></p>
    <p class="my-1"><span class="font-bold">vendor:</span> <span id="vendor">-</span></p>

    <h2 class="text-1xl my-4 italic underline">Feature Detection</h2>
    <p class="my-1"><span class="font-bold">Apple OS:</span> <span id="AppleOS">-</span></p>
    <p class="my-1"><span class="font-bold">Apple Device:</span> <span id="AppleDevice">-</span></p>
    <p class="my-1"><span class="font-bold">Device Detection:</span> <span id="DeviceDetection">-</span></p>
    <p class="my-1"><span class="font-bold">Browser:</span> <span id="Browser">-</span></p>
    <p class="my-1"><span class="font-bold">iOS Version:</span> <span id="iOSVersion">-</span></p>
  </div>

  <div class="m-16 text-xs text-center underline"><a href="https://linktr.ee/natterstefan" target="_blank">made with <span aria-label="a red heart" role="img">❤️</span> by @natterstefan</a></div>
</div>

2. You can customize the styling of the HTML elements using the provided CSS code in the original code snippet. Copy the CSS and include it in a <style> tag in the HTML file, or link it externally. (Optional)

body {
  margin: 1.75rem;
  background: #efefef;
}

3. The JavaScript code contains several functions that help detect browser information. Here’s a quick overview of each function’s purpose:

  • detectIosVersion(): Detects the iOS version.
  • detectAppleOs(): Identifies the user’s OS (macOS or iOS).
  • detectIosDevices(): Detects Apple devices.
  • detectDevice(): Distinguishes between iPhones, iPads, and desktops.
  • detectChrome(): Checks if the user’s browser is Chrome.
  • detectFirefox(): Detects Firefox.
  • detectBrowser(): Combines the above functions to identify the user’s browser.

Insert the JavaScript code just before the closing </body> tag in your HTML file:

/**
 * # Detect Current Apple Device (macOS or iOS) and Browser
 * (Chrome or not Chrome)
 *
 * Misc Notes
 * - https://github.com/DamonOehlman/detect-browser (not tested)
 */

/**
 * The problem with > iOS 13 in general is that it mimics the user agent of Macs.
 * Therefore it is difficult to get the correct iOS Version >= 13.
 * @see https://stackoverflow.com/a/57838385/1238150
 *
 * inspired by
 * @see https://codepen.io/niggi/pen/DtIfy
 */
function detectIosVersion() {
  if (/iP(hone|od|ad)/.test(navigator.platform)) {
    var v = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);

    const result = [
      parseInt(v[1], 10),
      parseInt(v[2], 10),
      parseInt(v[3] || 0, 10)
    ].join(".");

    return result;
  }

  return "-";
}

/**
 * Detect Apple OS by testing if `window.ontouchstart` exists
 *
 * @see https://stackoverflow.com/q/58019463/1238150
 *
 * Alternatives
 * - https://stackoverflow.com/a/57654258/1238150 (with `TouchEvent`)
 * - https://stackoverflow.com/a/60553965/1238150 (with `Canvas`)
 */
function detectAppleOs() {
  if (/Safari[\/\s](\d+\.\d+)/.test(window.navigator.userAgent)) {
    return "ontouchstart" in window ? "iOS" : "macOS";
  }

  if (window.navigator.platform === "MacIntel") {
    return "macOS";
  }

  return "No Apple Device";
}

/**
 * Apple Device detection with >iOS13 support
 *
 * What is `navigator.standalone`?
 * > Returns a boolean indicating whether the browser is running in standalone mode.
 * > Available on Apple's iOS Safari only.
 * > (https://developer.mozilla.org/de/docs/Web/API/Navigator)
 *
 * @see https://stackoverflow.com/a/62980780/1238150
 * @see https://racase.com.np/javascript-how-to-detect-if-device-is-ios/
 *
 * Misc:
 * - detect if site is running in standalone (added to home screen):
 *   https://stackoverflow.com/a/40932368/1238150
^ */
function detectIosDevices() {
  // devices prior to iOS 13
  if (/iPad|iPhone|iPod/.test(navigator.platform)) {
    return navigator.platform;
  }

  // or with document.createEvent('TouchEvent'), which is only available on iPads (and iPhones)
  return !!(
    navigator.platform === "MacIntel" &&
    typeof navigator.standalone !== "undefined"
  )
    ? "iPad"
    : navigator.platform === "MacIntel"
    ? "Macbook"
    : "No Apple Device";
}

/**
 * Detects iPhone, iPad and Desktop computer
 *
 * inspired by
 * @see https://stackoverflow.com/a/59016446/1238150 (Nov. 2019)
 */
function detectDevice() {
  var agent = window.navigator.userAgent;

  // iPhone
  IsIPhone = agent.match(/iPhone/i) != null;

  // iPad up to IOS12
  IsIPad = agent.match(/iPad/i) != null;

  if (IsIPad) {
    IsIPhone = false;
  }

  // iPad from IOS13
  var macApp = agent.match(/Macintosh/i) != null;

  // also used in https://stackoverflow.com/a/60553965/1238150
  if (macApp) {
    // need to distinguish between Macbook and iPad
    var canvas = document.createElement("canvas");
    if (canvas != null) {
      var context =
        canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
      if (context) {
        var info = context.getExtension("WEBGL_debug_renderer_info");
        if (info) {
          var renderer = context.getParameter(info.UNMASKED_RENDERER_WEBGL);
          if (renderer.indexOf("Apple") != -1) {
            IsIPad = true;
          }
        }
      }
    }
  }

  if (IsIPhone) {
    return "iPhone";
  } else if (IsIPad) {
    return "iPad";
  } else {
    // right now we do not distinguish between the two of them
    return "Desktop computer";
  }
}

/**
 * Detects if current Browser is Chrome. Also works on iOS devices.
 */
function detectChrome() {
  // http://browserhacks.com/
  // https://stackoverflow.com/a/9851769/1238150
  const isChrome =
    !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);

  // https://stackoverflow.com/a/37178303/1238150
  return /Chrome|CriOS/i.test(navigator.userAgent) || isChrome;
}

function detectFirefox() {
  return /Firefox|FxiOS/i.test(navigator.userAgent);
}

function detectBrowser() {
  if (detectChrome()) {
    return "Chrome";
  }
  if (detectFirefox()) {
    return "Firefox";
  }

  // Attention: catchall-fallback with no guarantee
  return "Safari";
}

// DOMContentLoaded
// @see https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
document.addEventListener("DOMContentLoaded", function () {
  // navigator
  document.getElementById("useragent").innerText = navigator.userAgent || "-";
  document.getElementById("platform").innerText = navigator.platform || "-";
  document.getElementById("appVersion").innerText = navigator.appVersion || "-";
  document.getElementById("vendor").innerText = navigator.vendor || "-";

  // feature detection
  document.getElementById("AppleOS").innerText = detectAppleOs();
  document.getElementById("AppleDevice").innerText = detectIosDevices();
  document.getElementById("DeviceDetection").innerText = detectDevice();
  document.getElementById("Browser").innerText = detectBrowser();
  document.getElementById("iOSVersion").innerText = detectIosVersion();
});

You’ve successfully implemented JavaScript code to detect browser names and versions. This valuable data can help you optimize your website for a better user experience, ensuring compatibility with various browsers and devices. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X