How to Detect Mac OS X Version in JavaScript

China☆狼群 提交于 2019-12-07 07:49:27

问题


I have scoured everywhere on the internet as to how to detect the OS and it's version. I have found out how to do it for windows, (see code below), and now I want it to work for Mac too.

Windows detection code (works perfectly!):

// OS detection
var _os_ = (function(){
var userAgent = navigator.userAgent.toLowerCase();
return {
    isWin2K: /windows nt 5.0/.test(userAgent),
    isXP: /windows nt 5.1/.test(userAgent),
    isVista: /windows nt 6.0/.test(userAgent),
    isWin7: /windows nt 6.1/.test(userAgent),
};
}());

// get OS shorthand names

var OS;
if(_os_.isWin2K){
OS = "Windows 2000";
}

if(_os_.isXP){
OS = "Windows XP";
}

if(_os_.isVista){
OS = "Windows Vista";
}

if(_os_.isWin7){
OS = "Windows 7";
}

alert(OS);

So I'm wondering if it's possible to do this SAME thing for Mac OS X. Like,

 ...
 return {
     isMac10.5: /mac osx 10.5/.test(userAgent),
     isMac10.6: /mac osx 10.6/.test(userAgent),
     isMac10.7: /mac osx 10.7/.test(userAgent),
     isMac10.8: /mac osx 10.8/.test(userAgent),
 };

 ....
 if(_os_.isMac10.5){
 OS = "Mac OS X Leopard";
 }

 etc., etc...

Any ideas? Any help would be much appreciated!


回答1:


return {
     isMac105: /Mac OS X 10_5/.test(userAgent),
     isMac106: /Mac OS X 10_6/.test(userAgent),
     isMac107: /Mac OS X 10_7/.test(userAgent),
     isMac108: /Mac OS X 10_8/.test(userAgent),
 };

useragent for mac e.g.

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_1) AppleWebKit/536.25 (KHTML, like Gecko) Version/6.0 Safari/536.25

Macintosh; U; Intel Mac OS X 10_5_8; ru) AppleWebKit/533.18.1 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5




回答2:


Yeah it's because on Firefox the OSX Version is not listed as 10_6 but 10.6 So you have to add that specific line : isMac106: /Mac OS X 10.6/.test(userAgent)

Pay attention to the dot between 10 and 6



来源:https://stackoverflow.com/questions/12451382/how-to-detect-mac-os-x-version-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!