Detect the Device's Operating System in JavaScript

When developing software, different operating systems may be involved and some conditions may be added depending on this situation. The browser's navigator object can be a saviour in this special scenario.

The navigator object holds a significant amount of device information such as appName, appCodeName, platform, userAgent and so on. Among all this, you can use the userAgent property, which holds information about the browser and the operating system it runs on. 

When you run the navigator.userAgent command in the browser console, you will see a string like the following:

Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36

As you can see, the result here returned information about my current browser. Most importantly, however, it also returned the operating system. In my case this is Linux.

What we need to do next is to use the match() method on navigator.userAgent to check if this property matches the desired operating system.

if (navigator.userAgent.match(/Linux/i)) {

    // Do things related to Linux

} else if (navigator.userAgent.match(/Windows/i)) {

    // Do things related to Windows

} else if (navigator.userAgent.match(/Mac/i)) {

    // do things related to macOS

}

That's all there is to it.

No comments yet

Leave a Reply

Your email address will not be published. Required fields are marked *