Home > Web Front-end > JS Tutorial > How Can I Detect the User's Operating System Name and Version Using JavaScript?

How Can I Detect the User's Operating System Name and Version Using JavaScript?

Susan Sarandon
Release: 2024-11-30 05:48:10
Original
987 people have browsed it

How Can I Detect the User's Operating System Name and Version Using JavaScript?

Determining the Operating System Details Using JavaScript

JavaScript provides various mechanisms to determine the user's operating system (OS) name and version:

  1. Navigator Object:

    • navigator.userAgent property contains information about the user's device and software, including the OS.
  2. Platform Object:

    • navigator.platform property provides additional information about the system platform, which can be used to infer the OS.

To obtain both the OS name and version using JavaScript, you can employ the following code snippet:

const osName = navigator.userAgent.match(/Mac|Win|Linux/g).join('');
const osVersion = navigator.userAgent.match(/\d+(\.\d+)+/g).join('.');
Copy after login

This code identifies the OS name (e.g., "Mac", "Win", or "Linux") and its version (e.g., "10.15.1") by extracting and combining the relevant data from the user agent string.

Here's an example of using this code to detect and display the OS details:

const osInfo = getOSInfo();
console.log(`OS Name: ${osInfo.name}`);
console.log(`OS Version: ${osInfo.version}`);

function getOSInfo() {
  const osName = navigator.userAgent.match(/Mac|Win|Linux/g).join('');
  const osVersion = navigator.userAgent.match(/\d+(\.\d+)+/g).join('.');
  return { name: osName, version: osVersion };
}
Copy after login

This approach provides a simple and reliable way to access the OS details in JavaScript.

The above is the detailed content of How Can I Detect the User's Operating System Name and Version Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template