What is the Best way to do Browser Detection in Javascript?

前端 未结 8 1798
自闭症患者
自闭症患者 2020-12-05 16:55

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.

相关标签:
8条回答
  • 2020-12-05 17:16

    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.

    0 讨论(0)
  • 2020-12-05 17:18

    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.

    0 讨论(0)
  • 2020-12-05 17:19

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

    0 讨论(0)
  • 2020-12-05 17:22

    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.

    0 讨论(0)
  • 2020-12-05 17:25

    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

    0 讨论(0)
  • 2020-12-05 17:26

    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);
    });
    
    0 讨论(0)
提交回复
热议问题