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>