当我看到浏览器的控制台时,即使我使用的是 Windows,它也会返回 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';
}
代码或我的控制台有任何问题吗?
我尝试使用其他浏览器和电脑,但不起作用!!!
您应该使用
navigator.platform
而不是 navigator.userAgent
。您可以在 MDN Web 文档 中了解更多信息
请注意,此功能已被弃用,不再推荐
function detectOS() {
const userAgent = navigator.platform.toLowerCase();
if (userAgent.includes('win')) {
return 'Windows';
} else if (userAgent.includes('mac')) {
return 'Mac';
} else if (userAgent.includes('linux')) {
return 'Linux';
}
return 'Unknown OS';
}
希望这能解决您的问题!