How to Detect the Operating System (OS) Using JavaScript
Sometimes it is necessary to detect the user’s operating system when building web applications or websites. This can be useful for applying different CSS styles, collecting analytics data, or adapting certain features depending on the user’s environment. While there are many libraries and plugins available for OS detection, in simple cases it is вполне possible to implement this functionality without any third-party tools.
In most situations, you do not need to detect the exact version of the operating system — knowing its general type is enough. The most common operating systems you may want to handle are Windows, macOS, Linux, Android, and iOS. These platforms cover the majority of users and are usually sufficient for practical frontend tasks.
There are several real-world use cases for detecting the operating system. For example, you may want to display different download links depending on whether the user is on Windows or macOS. Another common scenario is adjusting UI behavior or showing platform-specific instructions. In some cases, OS detection can also be used to improve user experience by tailoring content or functionality to match the user’s device.
JavaScript
function detectOS() {
const platform = navigator.platform.toLowerCase(),
iosPlatforms = ['iphone', 'ipad', 'ipod', 'ipod touch'];
if (platform.includes('mac')) return 'MacOS';
if (iosPlatforms.includes(platform)) return 'iOS';
if (platform.includes('win')) return 'Windows';
if (/android/.test(navigator.userAgent.toLowerCase())) return 'Android';
if (/linux/.test(platform)) return 'Linux';
return 'unknown';
}
The approach described here does not aim to cover every possible operating system, but focuses on the most widely used ones. At the same time, the logic can be easily extended or modified if you need to support additional platforms in the future.
You can see an example of the code working on Codepen: https://codepen.io/igorrybalko/pen/vEBvPgm
Similar posts:
-
Drop down menu (jQuery)
Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay i...
-
How to Make Asynchronous Requests in a Loop in JavaScript
Implementing asynchronous requests inside a JavaScript loop may not seem obvious at first. When making asynchronous requests inside a JavaScript loop, it is important to ...
-
Finding the Distance Between Two Points on a Map Using JavaScript (TypeScript)
If you have the coordinates of two points on a map, calculating the distance between them is a fairly straightforward task. This type of calculation is commonly used in m...
Very interesting subject, appreciate it for posting.