How can you detect the version of a browser?

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

    Adding my own implementation of Hermann's answer. I needed OS detection so that's been added. Also includes some ES6 code (because we have a transpiler) that you might need to ES5-ify.

    detectClient() {
        let nav = navigator.appVersion,
            os = 'unknown',
            client = (() => {
                let agent = navigator.userAgent,
                    engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
                    build;
    
                if(/trident/i.test(engine[1])){
                    build = /\brv[ :]+(\d+)/g.exec(agent) || [];
                    return {browser:'IE', version:(build[1] || '')};
                }
    
                if(engine[1] === 'Chrome'){
                    build = agent.match(/\bOPR\/(\d+)/);
    
                    if(build !== null) {
                        return {browser: 'Opera', version: build[1]};
                    }
                }
    
                engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];
    
                if((build = agent.match(/version\/(\d+)/i)) !== null) {
                    engine.splice(1, 1, build[1]);
                }
    
                return {
                  browser: engine[0],
                  version: engine[1]
                };
            })();
    
        switch (true) {
            case nav.indexOf('Win') > -1:
                os = 'Windows';
            break;
            case nav.indexOf('Mac') > -1:
                os = 'MacOS';
            break;
            case nav.indexOf('X11') > -1:
                os = 'UNIX';
            break;
            case nav.indexOf('Linux') > -1:
                os = 'Linux';
            break;
        }        
    
        client.os = os;
        return client;
    }
    

    Returns: Object {browser: "Chrome", version: "50", os: "UNIX"}

提交回复
热议问题