How to detect Safari, Chrome, IE, Firefox and Oper

2018-12-31 00:27发布

I have 5 addons / extensions for FF, Chrome, IE, Opera and Safari.

I need the code to recognize the user browser and redirect (on click in an install button) to download the corresponding addon.

17条回答
看淡一切
2楼-- · 2018-12-31 00:34

I know it may be overkill to use a lib for that, but just to enrich the thread, you could check is.js way of doing this:

is.firefox();
is.ie(6);
is.not.safari();
查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 00:38

UAParser is one of the lightweight JavaScript Library to identify browser, engine, OS, CPU, and device type/model from userAgent string.

There's an CDN available. Here, I have included a example code to detect browser using UAParser.

<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/ua-parser-js@0/dist/ua-parser.min.js"></script>
<script type="text/javascript">
    var parser = new UAParser();
    var result = parser.getResult();
    console.log(result.browser);     // {name: "Chromium", version: "15.0.874.106"}
</script>
</head>
<body>
</body>
</html>

Now you can use the value of result.browser to conditionally program your page.

Source Tutorial: How to detect browser, engine, OS, CPU, and device using JavaScript?

查看更多
公子世无双
4楼-- · 2018-12-31 00:40

In case anyone finds this useful, I've made Rob W's answer into a function that returns the browser string rather than having multiple variables floating about. Since the browser also can't really change without loading all over again, I've made it cache the result to prevent it from needing to work it out the next time the function is called.

/**
 * Gets the browser name or returns an empty string if unknown. 
 * This function also caches the result to provide for any 
 * future calls this function has.
 *
 * @returns {string}
 */
var browser = function() {
    // Return cached result if avalible, else get result then cache it.
    if (browser.prototype._cachedResult)
        return browser.prototype._cachedResult;

    // Opera 8.0+
    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

    // Firefox 1.0+
    var isFirefox = typeof InstallTrigger !== 'undefined';

    // Safari 3.0+ "[object HTMLElementConstructor]" 
    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;

    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;

    // Chrome 1+
    var isChrome = !!window.chrome && !!window.chrome.webstore;

    // Blink engine detection
    var isBlink = (isChrome || isOpera) && !!window.CSS;

    return browser.prototype._cachedResult =
        isOpera ? 'Opera' :
        isFirefox ? 'Firefox' :
        isSafari ? 'Safari' :
        isChrome ? 'Chrome' :
        isIE ? 'IE' :
        isEdge ? 'Edge' :
        isBlink ? 'Blink' :
        "Don't know";
};

console.log(browser());

查看更多
其实,你不懂
5楼-- · 2018-12-31 00:40

Short variant

    var browser = (function(agent){
        switch(true){
            case agent.indexOf("edge") > -1: return "edge";
            case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
            case agent.indexOf("chrome") > -1 && !!window.chrome: return "chrome";
            case agent.indexOf("trident") > -1: return "ie";
            case agent.indexOf("firefox") > -1: return "firefox";
            case agent.indexOf("safari") > -1: return "safari";
            default: return "other";
        }
    })(window.navigator.userAgent.toLowerCase());
查看更多
冷夜・残月
6楼-- · 2018-12-31 00:40

This combines both Rob's original answer and Pilau's update for 2016

    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;
查看更多
只靠听说
7楼-- · 2018-12-31 00:41

No idea if it is useful to anyone but here is a variant to make TypeScript happy.

export function getBrowser() {

// Opera 8.0+
if ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0) {
    return 'opera';
}

// Firefox 1.0+
if (typeof window["InstallTrigger"] !== 'undefined') {
    return 'firefox';
}

// Safari 3.0+ "[object HTMLElementConstructor]" 
if (/constructor/i.test(window["HTMLElement"]) || (function(p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof window["safari"] !== 'undefined' && window["safari"].pushNotification))) {
    return 'safari';
}

// Internet Explorer 6-11
if (/*@cc_on!@*/false || !!document["documentMode"]) {
    return 'ie';
}

// Edge 20+
if (!(/*@cc_on!@*/false || !!document["documentMode"]) && !!window["StyleMedia"]) {
    return 'edge';
}

// Chrome 1+
if (!!window["chrome"] && !!window["chrome"].webstore) {
    return 'chrome';
}

// Blink engine detection
if (((!!window["chrome"] && !!window["chrome"].webstore) || ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0)) && !!window["CSS"]) {
    return 'blink';
}

}

查看更多
登录 后发表回答