在 Javascript 中进行浏览器检测的最佳方法是什么?

发布于 2024-07-14 08:50:38 字数 439 浏览 13 评论 0原文

在我的一门 Web 开发课程中,我们要求创建一个脚本来检测 NE4、NE6+、IE4、IE6+ 浏览器,并为每个浏览器显示兼容的 CSS 脚本。

他给了我们一篇关于这些内容的文章,其中提到了这个网站

其中一位学生说这

javascript的最佳选择 兼容性是为了测试浏览器 当你想做的时候的能力 某物。 主要原因之一 因为在未来,更多 更多的浏览器将会被创建。

现在我的问题是,哪种方法是检测用户浏览器对象检测或使用导航器对象的最佳方法?

In one of my Web Development classes we where asked to create a script that detects NE4,NE6+,IE4,IE6+ Browsers that display a compatable CSS script for each browser.

he gave us an article to read about these and the article mentioned this site

one of the students said this

The best choice for javascript
compatibility is to test for browser
capabilities when you want to do
something. One of the main reasons
for this is that in the future, more
and more browsers will be created.

Now my questions is this which way is the best way to detect the users browser object detection or using the Navigator Object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

肥爪爪 2024-07-21 08:50:38

检测所使用的浏览器的标准方法是检查提供的用户代理。

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
               string: navigator.userAgent,
               subString: "iPhone",
               identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();

http://www.quirksmode.org/js/detect.html

The standard way to detect what browser is used is to check the user agent supplied.

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
               string: navigator.userAgent,
               subString: "iPhone",
               identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();

http://www.quirksmode.org/js/detect.html

凌乱心跳 2024-07-21 08:50:38

在我的 Web 开发课程之一中,我们要求创建一个检测 NE4、NE6+、IE4、IE6+ 的脚本

您的 Web 开发课程已经无可救药、可笑地过时了。

早在 Netscape4 和 IE4 还是通用浏览器的时候,通常需要嗅探浏览器类型并为它们提供不同的样式表和脚本,因为它们对样式和 DHTML 功能的支持非常不同。

如今,基准浏览器(您必须担心的质量最低的浏览器)无疑是 IE6。 几乎没有人使用比这更低的东西,因为 IE6 是随 XP 一起提供的,而未升级的 Win2K 和 Win9X 机器的使用量微乎其微。 当然,世界上没有人在使用 IE4 或糟糕的 Netscape 4。 当前很少有网站可以使用它们。

得益于 Web 标准,您可能想要定位的所有其他浏览器(IE7+、Firefox2+、Opera、Safari、Chrome、Konqueror)通常都足够接近互兼容性,因此您很少需要进行大量浏览器检测。 IE6 确实需要一些小心,但通常如果您使用标准模式,您可以通过一些 CSS hack(特别是“* html”)和脚本中的一些功能嗅探来完成,而不必为其提供完全不同的内容。

现在我的问题是,哪种方式是检测用户浏览器对象检测或使用导航器对象的最佳方式?

物体/方法检测。

尽可能避免使用导航器对象; 它通常出于兼容性目的而撒谎,并且扫描字符串以尝试计算出浏览器名称很容易在用户代理字符串中遇到意外的标记。

如果您需要专门检测 IE6(这是迄今为止最常见的浏览器,必须检测并为其添加解决方法),并且没有合适的功能嗅探方法,最好使用 条件编译 优于 navigator.userAgent 处理。

In one of my Web Development classes we where asked to create a script that detects NE4,NE6+,IE4,IE6+

Your web development class is hopelessly, laughably out of date.

Back in the days when Netscape4 and IE4 were common browsers, it was often necessary to sniff the browser type and serve them different stylesheets and scripts, because their support for styles and DHTML features was so very different.

These days the baseline browser, the lowest-quality one that you have to worry about, is firmly IE6. Almost no-one is using anything lower than that, because IE6 came with XP and the use of un-upgraded Win2K and Win9X boxes is vanishingly small. Certainly no-one in the universe is using IE4 or the awful Netscape 4; very few current web sites will even work on them.

Thanks to web standards, all the other browsers you might want to target (IE7+, Firefox2+, Opera, Safari, Chrome, Konqueror) are generally close enough to intercompatibility that you will rarely need to do much browser detection. IE6 does demand some care, but generally if you use Standards Mode you can get by with a few CSS hacks (specifically, “* html”) and some capability-sniffing in scripts, rather than have to serve up completely different content for it.

Now my questions is this which way is the best way to detect the users browser object detection or using the Navigator Object?

Object/method detection.

Avoid the navigator object whenever possible; it often lies for compatibility purposes, and scanning strings to try to work out browser names can easily trip up on unexpected tokens in the user-agent string.

In the event when you need to detect IE6 specifically (which is by far the most common browser to have to detect and add workarounds for), and there's no suitable way of capability sniffing, it's better to use conditional compilation than navigator.userAgent processing.

蓝眸 2024-07-21 08:50:38

最好的方法是尽可能避免使用依赖于浏览器的代码,但在绝对必要的情况下,使用由比你和我了解更多的人编写的已被证明正确的代码。我建议使用 JQuery,因为这是我的库选择,但还有很多其他选择(YUI 很流行,Scriptilicious 也很流行,等等)。 谷歌 JQuery 开始。 另外,谷歌搜索“John Resig at Google”,看看是否可以找到他所做的演讲,其中讨论了他用来检测浏览器功能的一些技术。 它非常聪明,因为它会随着浏览器解决遗留问题而进行调整。

The best way is to avoid using browser dependent code as much as possible, but where absolutely necessary, use code that has been proven correct written by people who know a lot more than you and I. I would suggest JQuery, as that's my library of choice, but there are plenty of others out there (YUI is popular, as is Scriptilicious, etc). Google JQuery to get started. Also, google 'John Resig at Google' to see if you can find a talk he did where he discusses some of the techniques he uses to detect browser capabilities. It's very clever, as it adapts as browsers fix their legacy issues.

归途 2024-07-21 08:50:38

1.3.2 中已弃用的 jQuery.browser() 将返回有用的信息...另请参阅 jQuery.support()

tho deprecated in 1.3.2 jQuery.browser() will return useful info ... also see jQuery.support()

轮廓§ 2024-07-21 08:50:38

最好的方法是不检测它,而是使用跨浏览器兼容的库,例如 jQuery。 这在表现力方面还有很多其他优势。

The best way is to not detect it, but to use a cross-browser-compatible library like jQuery. This also has a lot of other advantages in terms of expressiveness.

毁我热情 2024-07-21 08:50:38

老实说,如果您尝试检测浏览器,那么您遇到的问题是错误的。 我的建议是检测您想要使用的功能并据此进行降级。 例如,如果您需要创建 XMLHttpRequest,则类似于以下内容的内容将起作用:

  var xhr = null;
   if (typeof(XMLHttpRequest) !== 'undefined')
      xhr = new XMLHttpRequest(...);
   else if (typeof(ActiveXObject) !== 'undefined')
      xhr = new ActiveXObject('Microsoft.XMLHTTP');

   if (xhr != null)
      ...do something with it
   else
      throw "No XMLHttpRequest";

这种方法允许您的应用程序随着浏览器开始支持更多功能而增长。 显然,不言而喻,这些类型的检查应该在某个函数中抽象出来,以免一遍又一遍地用相同的检查乱扔代码。

但是,如果您能够使用 JQuery、Prototype、Dojo、YUI 等 Ajax 库,那么这可能是您最好的选择,因为它们已经内置了抽象。

Honestly, if you're trying to detect the browser you're attacking the wrong problem. My advice would be to detect the features that you want to use and degrade based on that. For example, if you need to create an XMLHttpRequest something similar to the following will work:

  var xhr = null;
   if (typeof(XMLHttpRequest) !== 'undefined')
      xhr = new XMLHttpRequest(...);
   else if (typeof(ActiveXObject) !== 'undefined')
      xhr = new ActiveXObject('Microsoft.XMLHTTP');

   if (xhr != null)
      ...do something with it
   else
      throw "No XMLHttpRequest";

This approach allows your applications to grow as the browsers start to support more features. Obviously, it goes without saying that these sorts of checks should be abstracted away in a function somewhere so as not to litter your code with the same checks over and over again.

However, if you're able to use an Ajax library like JQuery, Prototype, Dojo, YUI, etc that's probably your best bet as they already have the abstractions built in.

仙女 2024-07-21 08:50:38

我构建了一个简单的 Firefox Mac User Agent Detect,用于编写特定的 CSS。
http://www.combsconsulting.com/code-firefox-mac-hack。 html

I built a simple Firefox Mac User Agent Detect that writes specific CSS.
http://www.combsconsulting.com/code-firefox-mac-hack.html

似最初 2024-07-21 08:50:38

您需要使用 Conditionizr,它具有强大的测试/检测插件:http://conditionizr.com

例如:

conditionizr.add('safari', [], function () {
    return /constructor/i.test(window.HTMLElement);
});

You'll want to use Conditionizr, which features robust test/detect add-ons for this: http://conditionizr.com

For example:

conditionizr.add('safari', [], function () {
    return /constructor/i.test(window.HTMLElement);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文