如何在JavaScript中检测Mac OS X版本

时间:2012-09-16 22:50:52

标签: javascript macos browser operating-system detect

我已经在互联网上到处搜索如何检测操作系统及其版本。我已经找到了如何为Windows做到这一点,(见下面的代码),现在我希望它也能用于Mac。

Windows检测代码(效果很好!):

// 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);

所以我想知道是否可以为Mac OS X做同样的事情。比如,

 ...
 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...

有什么想法吗?任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

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),
 };

用于mac的useragent,例如

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

答案 1 :(得分:1)

是的,因为在Firefox上,OSX版本未列为10_6而是10.6因此您必须添加该特定行:isMac106:/ Mac OS X 10.6 / .test(userAgent)

注意10到6之间的点