JavaScript is unable to identify the operating system that is running underneath

Even though I am on a Windows system, the browser console is showing that I am using Linux.

function detectOS() {
    const userAgent = navigator.userAgent.toLowerCase();

    if (userAgent.includes('win')) {
        return 'Windows';
    } else if (userAgent.includes('mac')) {
        return 'Mac';
    } else if (userAgent.includes('linux')) {
        return 'Linux';
    } else if (userAgent.includes('iphone') || userAgent.includes('ipad')) {
        return 'iOS';
    } else if (userAgent.includes('android')) {
        return 'Android';
    }
  
    return 'Unknown OS';
}
console.log(detectOS());

Is there an issue with the code or my browser's console?

I have tried different browsers and PCs, but the issue persists!

Answer №1

Your code is designed to work in most scenarios, but there may be cases where certain browsers or browser extensions alter the user agent string, resulting in inaccurate information being provided. Therefore, these methods may not always be foolproof.1 Furthermore, if you are using a virtual machine, it might cause the user agent to display the host operating system instead of the guest OS.

You mentioned that using navigator.platform works for you, even though it is deprecated. In such cases, you can explore utilizing an alternative property like

navigator.userAgentData.platform.
2

As highlighted by JaromandaX in a comment, it is advisable to check for Linux as the final condition, since Android is a Linux-based operating system which could lead to conflicts.

Accurately verifying platform information can be challenging; hence, if you have the flexibility to leverage a library, consider using one that simplifies this process. Platform.js is a comprehensive library that offers solutions for this requirement.3

function detectOS() {
  // If a browser lacks support for navigator.userAgentData.platform, use platform as a fallback
  const userAgent = (navigator.userAgentData.platform ?? navigator.platform).toLowerCase();

  if (userAgent.includes('win')) {
    return 'Windows';
  } else if (userAgent.includes('android')) {
    return 'Android';
  } else if (userAgent.includes('mac')) {
    return 'Mac';
  } else if (userAgent.includes('iphone') || userAgent.includes('ipad')) {
    return 'iOS';
  } else if (userAgent.includes('linux')) {
    return 'Linux';
  }
  return 'Unknown OS';
}

console.log(detectOS());


1Exploring the Limitations of navigator.userAgent and navigator.platform:

Below is a simple script that uses navigator.platform to manipulate the platform property.

const codeToInject = `
  Object.defineProperty(navigator, "platform", {
    get: () => "MacIntel",
    set: (a) => {}
  });
`;
const script = document.createElement('script');
script.textContent = codeToInject;
(document.head || document.documentElement).appendChild(script);
script.remove();

console.log(navigator.platform); // Will consistently show MacIntel
// This experiment confirms that modifications can occur, as evidenced by the static output of Mac.

2Evaluating Browser Support:

Given that navigator.userAgentData is still experimental, it's essential to verify its browser compatibility.

3Utilizing platform.js for OS Detection:

Here's how you can implement platform.js for your OS detection needs.

function detectOS() { 
  const os = platform.os.family;

  if (os === 'Windows') {
    return 'Windows';
  } else if (os === 'OS X' || os === 'macOS') {
    return 'Mac';
  } else if (os === 'iOS') {
    return 'iOS';
  } else if (os === 'Android') {
    return 'Android';
  } else if (os === 'Linux') {
    return 'Linux';
  }

  return 'Unknown OS';
}

console.log(detectOS());
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.6/platform.min.js"></script>

Answer №2

Instead of relying on navigator.userAgent, it is recommended to use navigator.platform. For more information, you can refer to the MDN Web Docs

Note: This feature has been deprecated and is no longer advised for use.

function findOperatingSystem() {
        const userPlatform = navigator.platform.toLowerCase();

        if (userPlatform.includes('win')) {
            return 'Windows';
        } else if (userPlatform.includes('mac')) {
            return 'Mac';
        } else if (userPlatform.includes('linux')) {
            return 'Linux';
        }
      
        return 'Unknown OS';
    }

I hope this resolves your query!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The getStaticProps() function in next.js isn't retrieving items as expected

I've been facing issues while trying to load items onto my next.js page: import {getadminInfo} from '../../dataFetch/adminInfo' import {addItem} from '../../dataFetch/catalog' import {useState} from "react" import { getLi ...

Strategies for effectively engaging with dynamically created forms amidst a multitude of other forms on a webpage

One of the challenges I face is dealing with a page that has multiple forms dynamically generated based on user input. Each form contains two sets of radio buttons, with the second set being disabled by default and enabled based on the users' selectio ...

Encountering difficulties in importing TailwindCSS

Having trouble importing TailwindCSS and applying CSS? Here's how it's included in my package.json: "devDependencies": { "autoprefixer": "^10.2.4", "css-loader": "^5.1.1", "postc ...

How to use AJAX script to call a non-static page method in ASP.NET

Is it possible to achieve this task without utilizing the UpdatePanel feature? ...

How can I add a parameter to a JSON URL in Angular?

I'm looking to enhance my URL by adding a new parameter, but I'm unsure of the steps needed. ts.file route(name:string) { this.router.navigate(['/homepage', (name)]); console.log('name); } service private url1 = './assets/ ...

Vue.js computed property fails to initiate

Why is the Vue JS computed property not triggered with this markup? <!-- language: lang-html --> <p>£{{plant_price}}</p> <div v-if="selected.plant.variations.length > 0 "> <select v-model="selected.plant.selected_ ...

In Vue.js, you can utilize one property to access additional properties within the same element

Is it possible to access other properties of the same element using a different property in Vue.js? For example: Rather than writing it like this: <kpi title="some_kpi" v-if="displayed_kpi==='some_kpi'"></kpi> I ...

Issue with Angular's ngOnChanges Lifecycle Hook Preventing Function ExecutionWhen attempting to run a function within Angular's ngOn

In the midst of my evaluation process to ensure that specific values are properly transmitted from one component to another using Angular's custom Output() and EventEmitter(), I am encountering some issues. These values are being sent from the view of ...

Weaknesses found in the React Js library bundled with create-react-app

Each time I initiate a new react project using npx create-react-app <AppName>, the following vulnerabilities are detected: 96 vulnerabilities found - Packages audited: 1682 Severity: 65 Moderate | 30 High | 1 Critical Node Version: v14.18.1 Npm: 7.20 ...

Client-side resizing an image before sending it to PHP for uploading

Greetings! Currently, I am utilizing a JavaScript library from this source to resize images on the client-side. The image resizing process works successfully with the following code: document.getElementById('foto_select').onchange = function( ...

Obtain the name of the client's computer within a web-based application

I am working on a Java web application that requires the computer name of clients connecting to it. Initially, I attempted to retrieve this information using JavaScript and store it in a hidden form field. However, I discovered that JavaScript does not hav ...

I can't seem to figure out why my attempts to set a cookie through Express are failing

I am currently facing an issue with sending a cookie back to my React app after logging in. In my server, I have set up a test response: res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end(); In the app ...

Event triggered when a Socket.IO connection is disconnected

Everything seems to be working well with my code when a new user joins, but I'm encountering issues when a user leaves as it doesn't display anything. Can someone point out the error in my code? Below is my server-side code: const express = requ ...

Test your knowledge of Javascript with this innerHtml quiz and see

How can I display the output of a score from a three button radio button quiz without using an alert popup? I want the output to be displayed within a modal for a cleaner look. I tried using InnerHTML but now there is no output when the button is clicked. ...

Utilizing JMeter's WebDriver Sampler to Upload Firefox Profile

Currently, I am working on creating a JMeter script to measure the UI response time for different events using the WebDriver Sampler plugin. In my application, access to the GUI is restricted to certificate-authentication only. Therefore, my concern is wh ...

Making AJAX requests repeatedly within a loop

My current challenge involves implementing multiple ajax requests within a loop to populate several dropdown lists. Running the requests sequentially has resulted in only the last item in the loop being populated with values. var targetcontrols = []; ...

The AJAX call returned undefined, leading to an error when trying to access the length property

I've scoured various resources to find a solution for this issue, but unfortunately, I haven't had any luck with implementing the code. The problem lies with my JSON parser function, which is designed to construct a table based on data received ...

What are the steps to perform an Ajax request to an online web service?

I would like to send an AJAX request to an external web service using jQuery. However, I am encountering an error and unable to receive a successful response from the server. var url = "http://www.example.com/api/convert"; var requestData = { temperat ...

Combining multiple JSON strings into a single object using JavaScript

I am facing an issue with parsing a JSON output that contains two strings with specific formats: [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}] [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","senso ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...