JavaScript OS Platform Detection
The operating system platform on which JavaScript runs can be detected in both Node.js and browser environments.
In Node.js
Node.js provides two equivalent APIs to do this, one is process.platform
and the other is os.platform()
.
Its value is determined at compile time of Node.js, and current possible values are
'aix'
-
'android'
(Android support in Node.js is experimental) 'darwin'
'freebsd'
'linux'
'openbsd'
'sunos'
-
'win32'
(even for 64-bit Node.js)
In Browsers
In browsers, the platform can be retrieved via navigator.platform
, though its value is allowed to be an empty string by the spec, can be overridden by user preference on Firefox, or be overridden by other JavaScript code.
For a list of known values, refer to javascript - What is the list of possible values for navigator.platform as of today? - Stack Overflow.
Note: It is "Win32"
on Windows even for 64-bit browsers/OS like in the Node.js case.
As to override navigator.platform
mentioned above, it can be achieved via
// For Edge, Firefox, Chrome
Object.defineProperty(navigator, 'platform', { value: '' });
// For IE
Object.defineProperty(window, 'navigator', { value: { platform: '' } });
The value of platform (''
) in the code can be anything you want.