How can you detect the version of a browser?

后端 未结 28 2101
佛祖请我去吃肉
佛祖请我去吃肉 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:00

    I want to share this code I wrote for the issue I had to resolve. It was tested in most of the major browsers and works like a charm, for me!

    It may seems that this code is very similar to the other answers but it modifyed so that I can use it insted of the browser object in jquery which missed for me recently, of course it is a combination from the above codes, with little improvements from my part I made:

    (function($, ua){
    
    var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
        tem, 
        res;
    
    if(/trident/i.test(M[1])){
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        res = 'IE ' + (tem[1] || '');
    }
    else if(M[1] === 'Chrome'){
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem != null) 
            res = tem.slice(1).join(' ').replace('OPR', 'Opera');
        else
            res = [M[1], M[2]];
    }
    else {
        M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
        if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
        res = M;
    }
    
    res = typeof res === 'string'? res.split(' ') : res;
    
    $.browser = {
        name: res[0],
        version: res[1],
        msie: /msie|ie/i.test(res[0]),
        firefox: /firefox/i.test(res[0]),
        opera: /opera/i.test(res[0]),
        chrome: /chrome/i.test(res[0]),
        edge: /edge/i.test(res[0])
    }
    
    })(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);
    
     console.log($.browser.name, $.browser.version, $.browser.msie); 
    // if IE 11 output is: IE 11 true
    

提交回复
热议问题