When I see the console of my browser, even if i am using windows, it returns Linux.
function detectOS() {
const userAgent = navigator.userAgent.toLowerCase();
if (userAgent.includes('win')) {
return 'Windows';
} else if (userAgent.includes('mac')) {
return 'Mac';
} else if (userAgent.includes('linux')) {
return 'Linux';
} else if (userAgent.includes('iphone') || userAgent.includes('ipad')) {
return 'iOS';
} else if (userAgent.includes('android')) {
return 'Android';
}
return 'Unknown OS';
}
console.log(detectOS());
Any problem with the code or my console?
I tried to use other browser and PC, but not working!!!
2
Answers
You should use
navigator.platform
rather thannavigator.userAgent
. You can learn more about it in the MDN Web DocsDo note that this feature has been deprecated and is no longer recommended
Hope this solves your issue!
Your code should work for most cases. However, there might be instances where some browsers or browser extensions modify the user agent string, leading to incorrect information being returned. So they might not be the foolproof methods1. Additionally, if you are using a virtual machine, it could cause the user agent to report the host OS instead of the guest OS.
Since you mentioned that
navigator.platform
works for you, but also it is deprecated, you can consider using another property,navigator.userAgentData.platform
2.As pointed out by JaromandaX in a comment, you should check for Linux as the last condition, as Android is a Linux-based operating system so there might be some conflict.
Reliably checking platform information is not a trivial task; therefore, if you are allowed to use a library, I recommend using one that can handle this for you. Platform.js is a comprehensive library that can help you achieve this.
1Why
neither
navigator.userAgent
nornavigator.platform
are foolproof?I have created a small example using
navigator.platform
below which modifies theplatform
property.2Checking browser support
Since
navigator.userAgentData
is experimental it is important to check for its browser-support is crucial.