How can you detect the version of a browser?

后端 未结 28 2053
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:35

I\'ve been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but

相关标签:
28条回答
  • 2020-11-22 00:19

    The bowser JavaScript library offers this functionality.

    if (bowser.msie && bowser.version <= 6) {
      alert('Hello China');
    }
    

    It seems to be well maintained.

    0 讨论(0)
  • 2020-11-22 00:19

    I use this to get de Name and number (int) of the version of the actual browser:

    function getInfoBrowser() {
        var ua = navigator.userAgent, tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(M[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return { name: 'Explorer', version: parseInt((tem[1] || '')) };
        }
        if (M[1] === 'Chrome') {
            tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
            if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[1]) }; }
        }
        M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
        return {
            name: M[0],
            version: parseInt(M[1])
        };
    }
    
    function getBrowser(){
      let info = getInfoBrowser();
      $("#i-name").html(info.name);
      $("#i-version").html(info.version);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <input type="button" onclick="getBrowser();" value="Get Info Browser"/>
    <hr/>
    Name: <span id="i-name"></span><br/>
    Version: <span id="i-version"></span>

    This run in

    Chrome ; Firefox ; Safari ; Internet Explorer (>= 9) ; Opera ; Edge

    For me.

    0 讨论(0)
  • 2020-11-22 00:20

    Here is the java version for somemone who whould like to do it on server side using the String returned by HttpServletRequest.getHeader("User-Agent");

    It is working on the 70 different browser configuration I used for testing.

    public static String decodeBrowser(String userAgent) {
        userAgent= userAgent.toLowerCase();
        String name = "unknown";
        String version = "0.0";
        Matcher userAgentMatcher = USER_AGENT_MATCHING_PATTERN.matcher(userAgent);
        if (userAgentMatcher.find()) {
          name = userAgentMatcher.group(1);
          version = userAgentMatcher.group(2);
          if ("trident".equals(name)) {
            name = "msie";
            Matcher tridentVersionMatcher = TRIDENT_MATCHING_PATTERN.matcher(userAgent);
            if (tridentVersionMatcher.find()) {
              version = tridentVersionMatcher.group(1);
            }
          }
        }
        return name + " " + version;
      }
    
      private static final Pattern USER_AGENT_MATCHING_PATTERN=Pattern.compile("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*([\\d\\.]+)");
      private static final Pattern TRIDENT_MATCHING_PATTERN=Pattern.compile("\\brv[ :]+(\\d+(\\.\\d+)?)");
    
    0 讨论(0)
  • 2020-11-22 00:21

    Here are several prominent libraries that handle browser detection as of May 2019.

    Bowser by lancedikson - 3,761★s - Last updated May 26, 2019 - 4.8KB

    var result = bowser.getParser(window.navigator.userAgent);
    console.log(result);
    document.write("You are using " + result.parsedResult.browser.name +
                   " v" + result.parsedResult.browser.version + 
                   " on " + result.parsedResult.os.name);
    <script src="https://unpkg.com/bowser@2.4.0/es5.js"></script>

    *supports Edge based on Chromium


    Platform.js by bestiejs - 2,250★s - Last updated Oct 30, 2018 - 5.9KB

    console.log(platform);
    document.write("You are using " + platform.name +
                   " v" + platform.version + 
                   " on " + platform.os);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>

    jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB

    console.log($.browser)
    document.write("You are using " + $.browser.name +
                   " v" + $.browser.versionNumber + 
                   " on " + $.browser.platform);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>

    Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB

    var result = detect.parse(navigator.userAgent);
    console.log(result);
    document.write("You are using " + result.browser.family +
                   " v" + result.browser.version + 
                   " on " + result.os.family);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>

    Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B

    console.log(BrowserDetect)
    document.write("You are using " + BrowserDetect.browser +
                   " v" + BrowserDetect.version + 
                   " on " + BrowserDetect.OS);
    <script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>


    Notable Mentions:

    • WhichBrowser - 1,355★s - Last updated Oct 2, 2018
    • Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.

    Further Reading

    • Stack Overflow - Browser detection in JavaScript?
    • Stack Overflow - How to detect Safari, Chrome, IE, Firefox and Opera browser?
    0 讨论(0)
  • 2020-11-22 00:23

    Here this has better compatibility then @kennebec snippet;
    will return browser name and version (returns 72 instead of 72.0.3626.96).

    Tested on Safari, Chrome, Opera, Firefox, IE, Edge, UCBrowser, also on mobile.

    function browser() {
        var userAgent = navigator.userAgent,
            match = userAgent.match(/(opera|chrome|crios|safari|ucbrowser|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
            result = {},
            tem;
    
        if (/trident/i.test(match[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
            result.name = "Internet Explorer";
        } else if (match[1] === "Chrome") {
            tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
    
            if (tem && tem[1]) {
                result.name = tem[0].indexOf("Edge") === 0 ? "Edge" : "Opera";
            }
        }
        if (!result.name) {
            tem = userAgent.match(/version\/(\d+)/i); // iOS support
            result.name = match[0].replace(/\/.*/, "");
    
            if (result.name.indexOf("MSIE") === 0) {
                result.name = "Internet Explorer";
            }
            if (userAgent.match("CriOS")) {
                result.name = "Chrome";
            }
    
        }
        if (tem && tem.length) {
            match[match.length - 1] = tem[tem.length - 1];
        }
    
        result.version = Number(match[match.length - 1]);
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-22 00:23

    Detecting Browser and Its version

    This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.

    I have done few changes to detect browsers like Edge and UCBrowser

    getBrowser = () => {
        const userAgent = navigator.userAgent;
        let browser = "unkown";
        // Detect browser name
        browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
        browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
        browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
        browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
        browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
        browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
        browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
        browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
        browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
    
        // detect browser version
        switch (browser) {
            case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
            case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
            case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
            case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
            case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
            case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
            case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
            case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
            case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
                // IE version is mapped using trident version 
                // IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
                return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
            default: return `unknown/0.0.0.0`;
        }
    }
    
    browserVersion = (userAgent,regex) => {
        return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
    }
    
    console.log(getBrowser());

    0 讨论(0)
提交回复
热议问题