如何使用JavaScript找到操作系统名称和操作系统版本?


当前回答

路德维希的解决方案太棒了。有几个修复(与操作系统无关,我不能把他的原始帖子作为评论,因为这太长了):

IE 11不再自称为MS IE。 IOS上的Chrome把自己伪装成Safari

他们是:

(function (window) {
    {
    /* test cases
        alert(
            'browserInfo result: OS: ' + browserInfo.os +' '+ browserInfo.osVersion + '\n'+
                'Browser: ' + browserInfo.browser +' '+ browserInfo.browserVersion + '\n' +
                'Mobile: ' + browserInfo.mobile + '\n' +
                'Cookies: ' + browserInfo.cookies + '\n' +
                'Screen Size: ' + browserInfo.screen
        );
    */
        var unknown = 'Unknown';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        //browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }

        //IE 11 no longer identifies itself as MS IE, so trap it
        //http://stackoverflow.com/questions/17907445/how-to-detect-ie11
        else if ((browser == 'Netscape') && (nAgt.indexOf('Trident/') != -1)) {

            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
            if ((verOffset = nAgt.indexOf('rv:')) != -1) {
                version = nAgt.substring(verOffset + 3);
            }

        }

        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }

            // Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
            //  at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
            //  No mention of chrome in the user agent string. However it does mention CriOS, which presumably
            //  can be keyed on to detect it.
            if (nAgt.indexOf('CriOS') != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                //Don't believe there is a way to grab the accurate version number, so leaving that for now.
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 3.11', r:/Win16/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows ME', r:/Windows ME/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;

        }
    }

    window.browserInfo = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled
    };
}(this));

其他回答

我创建了一个用于解析User Agent字符串的库,名为Voodoo。但是要注意,不应该用它来代替特征检测。

Voodoo所做的是解析userAgent字符串,该字符串在Navigator对象(window.navigator)中找到。并不是所有浏览器都会传递可靠的userAgent字符串,所以即使这是正常的方式,userAgent也不总是可信的。

我不能评论@Ian Ippolito的回答(因为如果我有代表的话我会评论的),但根据他的评论链接,我相当确定你可以找到IOS的Chrome版本。https://developer.chrome.com/multidevice/user-agent?hl=ja列出的UA为:Mozilla/5.0 (iPhone;CPU iPhone OS 10_3像Mac OS X) AppleWebKit/602.1.50 (KHTML,像壁虎)CriOS/56.0.2924.75移动/14E5239e Safari/602.1

所以这应该是可行的:

if ((verOffset = nAgt.indexOf('CriOS')) != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                version = nAgt.substring(verOffset + 6);//should get the criOS ver.
            }

我还没能测试一下(否则我会改进他的答案),因为我的iPad在家里,而我在工作,但我想我应该把它放在那里。

如果您正在使用Electron创建网站或创建桌面应用程序,您可能需要获取客户端使用的操作系统的信息。在这种情况下,你可以使用全局属性window。navigator。 如果您使用console.log(navigator)在控制台中记录属性,您将看到包含浏览器、操作系统等信息的子属性的整个对象。

同样,如果你想创建一个本地NodeJS应用程序也是可以的!只需使用const os = require("os");;调用os模块。然后在控制台中记录常量。你会得到一个完整的对象,但如果你想看到平台的名称,你可以输入console.log(os.platform());,并确保在os后添加一对圆括号。平台作为平台在这里是一个功能!

希望这能有所帮助!

User-Agent字符串对于获取平台信息(OS, OS版本,cpu-arch等)不再可靠,因为可以重写它们,甚至浏览器的默认设置也不准确。 在浏览器控制台中尝试"console.log(navigator)"并检查User-Agent字段。

为了解决上述问题,W3有一个新的提议(https://wicg.github.io/ua-client-hints/),它将允许用户请求关于平台的特定信息。截至2021年5月11日,只有基于铬的浏览器(Chrome、Edge、Opera、Brave……)实现了该规范(该提案仍是非正式的)。

获取平台信息的一种方法是服务器通过向初始响应添加'Accept-CH: Sec-CH-UA-Platform-Version'这样的报头来请求特定的信息,来自客户端的任何后续请求都将包含平台信息报头。欲了解更多信息,请参阅上面的链接。

通过Javascript在客户端获取信息,下面的代码可以使用(复制并粘贴在chrome控制台)。

let platformDetails = await navigator.userAgentData.getHighEntropyValues(["architecture", 
"platform", "platformVersion", "model", "bitness", "uaFullVersion"]);
console.log(platformDetails);

如前所述,导航器。平台已弃用。我们应该使用导航器。但它仍然缺乏支持(firefox, safari在2022年不支持它)。

注意导航器。userAgentData只适用于通过https兼容的浏览器。

下面是一个脚本,它将使用UserAgentData,并返回到旧的操作方式。

function get_platform() {
    // 2022 way of detecting. Note : this userAgentData feature is available only in secure contexts (HTTPS)
    if (typeof navigator.userAgentData !== 'undefined' && navigator.userAgentData != null) {
        return navigator.userAgentData.platform;
    }
    // Deprecated but still works for most of the browser
    if (typeof navigator.platform !== 'undefined') {
        if (typeof navigator.userAgent !== 'undefined' && /android/.test(navigator.userAgent.toLowerCase())) {
            // android device’s navigator.platform is often set as 'linux', so let’s use userAgent for them
            return 'android';
        }
        return navigator.platform;
    }
    return 'unknown';
}

let platform = get_platform();

// examples of use
let isOSX = /mac/.test(platform.toLowerCase()); // Mac desktop
let isIOS = ['iphone', 'ipad', 'ipod'].indexOf(platform.toLowerCase()) !== -1; // Mac iOs
let isApple = isOSX || isIOS; // Apple device (desktop or iOS)
let isWindows = /win/.test(platform.toLowerCase()); // Windows
let isAndroid = /android/.test(platform.toLowerCase()); // Android
let isLinux = /linux/.test(platform.toLowerCase()); // Linux