简体   繁体   English

仅从userAgent中提取浏览器名称?

[英]Extract just browser name from userAgent?

I'm presenting a message (implemented with javascript) for users that goes along the lines of 我正在向用户展示一条消息(使用javascript实现)

Your browser is too old to view my page. 您的浏览器太旧,无法查看我的页面。 You are currently running: 您当前正在运行:

followed by the name of the user's browser. 后跟用户浏览器的名称。

Unfortunately the navigator.userAgent usually looks like this: 不幸的是, navigator.userAgent通常看起来像这样:

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)

The only bit of that that I need to spit back is MSIE 8.0 . 我需要吐的唯一一点是MSIE 8.0

Is there a regex somewhere out there that will more or less give me a sane, dumb-person friendly sanitization of the userAgent string? 是否有正则表达式会或多或少地为我提供对userAgent字符串的理智,愚蠢的友善清理? That works for a high percentage of browsers out in the wild. 这对于狂野的浏览器中的很大一部分来说都是有效的。

To get browser name and version from userAgent, you could do: 要从userAgent获取浏览器名称和版本,您可以执行以下操作:

function identifyBrowser() {
    var regexps = {
            'Chrome': [ /Chrome\/(\S+)/ ],
            'Firefox': [ /Firefox\/(\S+)/ ],
            'MSIE': [ /MSIE (\S+);/ ],
            'Opera': [
                /Opera\/.*?Version\/(\S+)/,
                /Opera\/(\S+)/
            ],
            'Safari': [ /Version\/(\S+).*?Safari\// ]
        },
        re, m, browser, version;

    userAgent = navigator.userAgent;
    elements = 2;
    for (browser in regexps)
        while (re = regexps[browser].shift())
            if (m = userAgent.match(re)) {
                version = (m[1].match(new RegExp('[^.]+(?:\.[^.]+){0,' + --elements + '}')))[0];
                return browser + ' ' + version);
            }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM