Languages
[Edit]
EN

JavaScript - check operating system (in web browser)

3 points
Created by:
Jacob
532

In this article, we would like to show you how to check the operating system in the web browser using JavaScript.

Practical example

In this example, we use navigator.platform property to detect current operating system by matching different strings.

// ONLINE-RUNNER:browser;

const conditions = {
    // conitions order is important
    'Windows':   ['Win64', 'Win32', 'Win'],
    'Linux x64': ['Linux x86_64'],
    'Linux x86': ['Linux x86'],
    'Linux ARM': ['Linux arm'],
    'Macintosh': ['MacIntel', 'Mac'],
    'iPhone':    ['iPhone']
};

let operatingSystem = null;

const detectOperatingSystem = () => {
    if (operatingSystem) {
        return operatingSystem;
    }
    const platform = navigator.platform;
    for (const key in conditions) {
        const texts = conditions[key];
        for (let i = 0; i < texts.length; ++i) {
            const index = platform.indexOf(texts[i]);
            if (index !== -1) {
                return operatingSystem = key;
            }
        }
    }
};


// Usage example:

console.log(detectOperatingSystem());

Warning:

Using the above approach, many Android devices are detected as Linux ARM devices. To solve the problem check this article

 

See also

  1. JavaScript - detect mobile device

  2. Example User-Agent values

References

  1. navigator.platform - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join