Home >Web Front-end >JS Tutorial >How Can I Identify a User's Browser and Version Using JavaScript?

How Can I Identify a User's Browser and Version Using JavaScript?

DDD
DDDOriginal
2024-12-09 07:21:09821browse

How Can I Identify a User's Browser and Version Using JavaScript?

Identifying Browser Details with JavaScript

Determining the exact browser and version using JavaScript can be achieved with the help of the navigator object. This object provides information about the user's browsing environment.

Solution:

To detect the browser and its version, you can utilize the following code snippet:

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

  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)');
    }
  }

  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);

Explanation:

  • The code extracts the user agent string from the navigator object.
  • It uses regular expressions to match the browser name and version.
  • For Internet Explorer, it checks for "trident" and extracts the version number from the "rv" field.
  • For Chrome, it checks for specific patterns to distinguish between Chrome, Opera, and Edge browsers.
  • The code then constructs a human-readable string representing the browser and version.
  • By calling console.log(navigator.saysWho), you can display the identified browser details in the console.

The above is the detailed content of How Can I Identify a User's 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