Home >Web Front-end >JS Tutorial >How Can I Reliably Detect Browser and Version Using JavaScript?

How Can I Reliably Detect Browser and Version Using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 17:00:15848browse

How Can I Reliably Detect Browser and Version Using JavaScript?

Browser Detection in JavaScript Revisited

Determining the exact browser and version using JavaScript can be a valuable tool for tailored web experiences. Here's how you can achieve this:

Navigator API:

The navigator property within JavaScript provides access to browser information. Its userAgent property contains a string that identifies the browser and its version.

Using Regex Expressions:

To extract the browser name and version from the userAgent string, you can utilize regular expressions. The following sample code uses a comprehensive regex to detect the various browsers and their versions:

navigator.saysWho = (() => {
  const { userAgent } = navigator;
  let match = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  let temp;

  // Handle special cases
  if (/trident/i.test(match[1])) {
    temp = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
    return `IE ${temp[1] || ''}`;
  }

  if (match[1] === 'Chrome') {
    temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
    if (temp !== null) {
      return temp.slice(1).join(' ').replace('OPR', 'Opera');
    }

    temp = userAgent.match(/\b(Edg)\/(\d+)/);
    if (temp !== null) {
      return temp.slice(1).join(' ').replace('Edg', 'Edge (Chromium)');
    }
  }

  // Construct the browser information string
  match = match[2] ? [match[1], match[2]] : [navigator.appName, navigator.appVersion, '-?'];
  temp = userAgent.match(/version\/(\d+)/i);
  if (temp !== null) {
    match.splice(1, 1, temp[1]);
  }

  return match.join(' ');
})();

console.log(navigator.saysWho); // outputs: `Chrome 89`

This script matches the user agent string against various browser patterns and returns the extracted browser and version as a string.

The above is the detailed content of How Can I Reliably Detect Browser and Version Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn