Wykrywanie przeglądarki w JavaScript? [duplikat]

To pytanie ma już odpowiedź tutaj:

Jak określić dokładną przeglądarkę i wersję za pomocą JavaScript?

Author: informatik01, 2010-03-08

26 answers

navigator.sayswho= (function(){
    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 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    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 M.join(' ');
})();

Jak sama nazwa wskazuje, to powie Ci nazwę i numer wersji dostarczonej przez przeglądarkę.

Jest to przydatne do sortowania wyników testów i błędów, gdy testujesz nowy kod w wielu przeglądarkach.

 341
Author: kennebec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-31 02:46:22

Polecam korzystanie z małej biblioteki javascript Bowser, tak nie r. jest on oparty na navigator.userAgent i dość dobrze przetestowany dla wszystkich przeglądarek, w tym iphone, android itp.

Https://github.com/ded/bowser

Możesz użyć po prostu powiedzieć:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello IE');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if (bowser.chrome){
  alert('Hello Chrome');
} else if (bowser.safari){
  alert('Hello Safari');
} else if(bowser.iphone || bowser.android){
  alert('Hello mobile');
}
 55
Author: arikan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-31 16:29:26

To jest coś, co napisałem, aby uzyskać informacje o kliencie

var ua = navigator.userAgent.toLowerCase();
var check = function(r) {
    return r.test(ua);
};
var DOC = document;
var isStrict = DOC.compatMode == "CSS1Compat";
var isOpera = check(/opera/);
var isChrome = check(/chrome/);
var isWebKit = check(/webkit/);
var isSafari = !isChrome && check(/safari/);
var isSafari2 = isSafari && check(/applewebkit\/4/); // unique to
// Safari 2
var isSafari3 = isSafari && check(/version\/3/);
var isSafari4 = isSafari && check(/version\/4/);
var isIE = !isOpera && check(/msie/);
var isIE7 = isIE && check(/msie 7/);
var isIE8 = isIE && check(/msie 8/);
var isIE6 = isIE && !isIE7 && !isIE8;
var isGecko = !isWebKit && check(/gecko/);
var isGecko2 = isGecko && check(/rv:1\.8/);
var isGecko3 = isGecko && check(/rv:1\.9/);
var isBorderBox = isIE && !isStrict;
var isWindows = check(/windows|win32/);
var isMac = check(/macintosh|mac os x/);
var isAir = check(/adobeair/);
var isLinux = check(/linux/);
var isSecure = /^https/i.test(window.location.protocol);
var isIE7InIE8 = isIE7 && DOC.documentMode == 7;

var jsType = '', browserType = '', browserVersion = '', osName = '';
var ua = navigator.userAgent.toLowerCase();
var check = function(r) {
    return r.test(ua);
};

if(isWindows){
    osName = 'Windows';

    if(check(/windows nt/)){
        var start = ua.indexOf('windows nt');
        var end = ua.indexOf(';', start);
        osName = ua.substring(start, end);
    }
} else {
    osName = isMac ? 'Mac' : isLinux ? 'Linux' : 'Other';
} 

if(isIE){
    browserType = 'IE';
    jsType = 'IE';

    var versionStart = ua.indexOf('msie') + 5;
    var versionEnd = ua.indexOf(';', versionStart);
    browserVersion = ua.substring(versionStart, versionEnd);

    jsType = isIE6 ? 'IE6' : isIE7 ? 'IE7' : isIE8 ? 'IE8' : 'IE';
} else if (isGecko){
    var isFF =  check(/firefox/);
    browserType = isFF ? 'Firefox' : 'Others';;
    jsType = isGecko2 ? 'Gecko2' : isGecko3 ? 'Gecko3' : 'Gecko';

    if(isFF){
        var versionStart = ua.indexOf('firefox') + 8;
        var versionEnd = ua.indexOf(' ', versionStart);
        if(versionEnd == -1){
            versionEnd = ua.length;
        }
        browserVersion = ua.substring(versionStart, versionEnd);
    }
} else if(isChrome){
    browserType = 'Chrome';
    jsType = isWebKit ? 'Web Kit' : 'Other';

    var versionStart = ua.indexOf('chrome') + 7;
    var versionEnd = ua.indexOf(' ', versionStart);
    browserVersion = ua.substring(versionStart, versionEnd);
}else{
    browserType = isOpera ? 'Opera' : isSafari ? 'Safari' : '';
}
 31
Author: Arun P Johny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-08 11:50:44

Oto jak wykrywać przeglądarki w 2016 roku, w tym Microsoft Edge, Safari 10 i wykrywanie mrugnięcia:

// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;
Piękno tego podejścia polega na tym, że opiera się ono na właściwościach silnika przeglądarki, więc obejmuje nawet pochodne przeglądarki, takie jak Yandex lub Vivaldi, które są praktycznie kompatybilne z głównymi przeglądarkami, których silniki używają. Wyjątkiem jest Opera, która polega na sniffingu user agent, ale obecnie (np. ver. 15 i więcej) nawet Opera sama w sobie jest tylko powłoką dla Blink.
 22
Author: pilau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-08 10:00:15

Zazwyczaj najlepiej jest unikać kodu specyficznego dla przeglądarki, jeśli to możliwe. Właściwość JQuery $.support jest dostępna do wykrywania obsługi określonych funkcji, a nie polegania na nazwie i wersji przeglądarki.

Na przykład w operze można sfałszować instancję internet Explorera lub Firefoksa.

alt text

Szczegółowy opis JQuery.wsparcie można znaleźć tutaj: http://api.jquery.com/jQuery.support/

Now deprecated according to jQuery.

Zdecydowanie zalecamy korzystanie z zewnętrznej biblioteki, takiej jak Modernizr zamiast zależności od właściwości w jQuery.support.

Podczas kodowania stron internetowych zawsze upewniam się, że podstawowe funkcje, takie jak nawigacja, są dostępne również dla użytkowników spoza js. Może to być obiektem dyskusji i może zostać zignorowane, jeśli strona główna jest skierowana do specjalnej grupy odbiorców.

 16
Author: Phil Rykoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-08 14:22:19

To informuje o wszystkich szczegółach dotyczących przeglądarki i jej wersji.

<!DOCTYPE html>
<html>
<body>
<div id="example"></div>

<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

</body>
</html>
 12
Author: malcolmX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-25 09:43:24

Wszystkie informacje o przeglądarce internetowej zawarte są w obiekcie navigator. Nazwa i Wersja są tam.

var appname = window.navigator.appName;

Source: javascript browser detection

 8
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-04 09:15:49
//Copy and paste this into your code/text editor, and try it

//Before you use this to fix compatability bugs, it's best to try inform the browser provider that you have found a bug and there latest browser may not be up to date with the current web standards

//Since none of the browsers use the browser identification system properly you need to do something a bit like this

//Write browser identification
document.write(navigator.userAgent + "<br>")

//Detect browser and write the corresponding name
if (navigator.userAgent.search("MSIE") >= 0){
    document.write('"MS Internet Explorer ');
    var position = navigator.userAgent.search("MSIE") + 5;
    var end = navigator.userAgent.search("; Windows");
    var version = navigator.userAgent.substring(position,end);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Chrome") >= 0){
document.write('"Google Chrome ');// For some reason in the browser identification Chrome contains the word "Safari" so when detecting for Safari you need to include Not Chrome
    var position = navigator.userAgent.search("Chrome") + 7;
    var end = navigator.userAgent.search(" Safari");
    var version = navigator.userAgent.substring(position,end);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Firefox") >= 0){
    document.write('"Mozilla Firefox ');
    var position = navigator.userAgent.search("Firefox") + 8;
    var version = navigator.userAgent.substring(position);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0){//<< Here
    document.write('"Apple Safari ');
    var position = navigator.userAgent.search("Version") + 8;
    var end = navigator.userAgent.search(" Safari");
    var version = navigator.userAgent.substring(position,end);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Opera") >= 0){
    document.write('"Opera ');
    var position = navigator.userAgent.search("Version") + 8;
    var version = navigator.userAgent.substring(position);
    document.write(version + '"');
}
else{
    document.write('"Other"');
}

//Use w3schools research the `search()` method as other methods are availible
 6
Author: Wayne Bulmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-17 09:27:10

Ponieważ wyszedł Internet Explorer 11 (IE11+) i nie używa już nazwy tagu MSIE wymyśliłem wariancję starszej funkcji wykrywania:

navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;

    // if IE11+
    if (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(ua) !== null) {
        var M= ["Internet Explorer"];
        if(M && (tem= ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/))!= null) M[2]= tem[1];
        M= M? [M[0], M[2]]: [N, navigator.appVersion,'-?'];
        return M;
    }

    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
})();
 6
Author: ghiscoding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-30 05:07:25

Niestety IE11 nie ma już MSIE w swoim navigator.userAgent:

Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; .NET4.0C; BRI/2; BOIE9;ENUS; rv:11.0) like Gecko

Jeśli chodzi o to, dlaczego chcesz wiedzieć, której przeglądarki używasz, to dlatego, że każda przeglądarka ma swój własny zestaw błędów, a ty w końcu implementujesz obejścia dotyczące przeglądarki i wersji lub mówisz użytkownikowi, aby używał innej przeglądarki!

 5
Author: user2183078,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-20 20:37:56
var browser = navigator.appName;
var version = navigator.appVersion;

Zauważ jednak, że oba nie muszą odzwierciedlać prawdy. Wiele przeglądarek można ustawić na maskowanie jak inne przeglądarki. Tak więc, na przykład, nie zawsze możesz być pewien, czy użytkownik rzeczywiście surfuje z IE6 lub z Operą, która udaje IE6.

 4
Author: ЯegDwight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-08 11:35:27

Ta mała biblioteka może Ci pomóc. Należy jednak pamiętać, że wykrywanie przeglądarki nie zawsze jest rozwiązaniem.

 3
Author: Fabien Ménager,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-08 11:42:38

Oto jak robię Niestandardowy CSS dla Internet Explorera:

W moim pliku JavaScript:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

A następnie w moim pliku CSS, y zdefiniować każdy inny styl:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}
 3
Author: Francisco Corrales Morales,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-22 02:28:22

Jeśli chcesz funkcji, która zwraca przeglądarkę, jak również wersję, oto ulepszenie w stosunku do oryginalnej odpowiedzi:

navigator.browserInfo = 
(
    function()
    {
        var browser = '';
        var version = '';
        var idString = '';

        var ua = navigator.userAgent;
        var tem = [];
        var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i);

        //IE will be identified as 'Trident' and a different version number. The name must be corrected to 'Internet Explorer' and the correct version identified.
        //ie correction
        if(/trident/i.test(M[1]))
        {
            tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
            browser = 'Internet Explorer';
            version = tem[1];
        }

        //firefox
        else if(/firefox/i.test(M[1]))
        {
            tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
            browser = 'Firefox';
            version = tem[1];
        }

        //safari
        else if(/safari/i.test(M[1]))
        {
            tem = ua.match(/\bVersion\/(\d+.?\d*\s*\w+)/);
            browser = 'Safari';
            version = tem[1];
        }

        //If 'Chrome' is found, it may be another browser. 
        else if(M[1] === 'Chrome')
        {
            //opera
            var temOpr = ua.match(/\b(OPR)\/(\d+.?\d*.?\d*.?\d*)/);
            //edge
            var temEdge = ua.match(/\b(Edge)\/(\d+.?\d*)/);
            //chrome
            var temChrome = ua.match(/\b(Chrome)\/(\d+.?\d*.?\d*.?\d*)/);

            //a genuine 'Chrome' reading will result from ONLY temChrome not being null.
            var genuineChrome = temOpr == null && temEdge == null && temChrome != null;

            if(temOpr != null)
            {
                browser = temOpr[1].replace('OPR', 'Opera');
                version = temOpr[2];
            }

            if(temEdge != null)
            {
                browser = temEdge[1];
                version = temEdge[2];
            }

            if(genuineChrome)
            {
                browser = temChrome[1];
                version = temChrome[2];
            }
        }
        //There will be some odd balls, so if you wish to support those browsers, add functionality to display those browsers as well.

        if(browser == '' || version == '')
        {
            idString = 'We couldn\'t find your browser, but you can still use the site';
        }
        else
        {
            idString = browser + ' version ' + version;
        }

        alert('Your browser is ' + idString);

        //store the type of browser locally
        if(typeof(Storage) !== "undefined")
        {
            //Store
            localStorage.setItem('browser', browser);
            localStorage.setItem('version', version);
        } 
        else
        {
            alert('local storage not available');
        }
    }
)();

Z tym, również przechowuje wynik lokalnie, więc ta kontrola nie jest konieczna do uruchomienia za każdym razem.

 2
Author: Shafiqul Islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-22 12:41:24

Możesz użyć biblioteki jQuery do wykrycia wersji przeglądarki.

Przykład:

JQuery.przeglądarka.Wersja

Jednak ma to sens tylko wtedy, gdy używasz również innych funkcji jQuery. Dodanie całej biblioteki, aby wykryć przeglądarkę, wydaje mi się przesadą.

Więcej informacji: http://api.jquery.com/jQuery.browser/

(musisz trochę przewinąć w dół)

 1
Author: user288744,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-08 12:29:46
 var isOpera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 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;                          // Chrome 1+
        var isIE = /*@cc_on!@*/false; 

Możesz przeczytać więcej Jak wykryć przeglądarkę Safari, Chrome, IE,Firefox i Opera?

 1
Author: chetan singhal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:54:44

Zamiast twardego kodowania przeglądarek internetowych, możesz zeskanować user agent, aby znaleźć nazwę przeglądarki:

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+/g)[0]
Testowałem to na Safari, Chrome i Firefox. Daj mi znać, jeśli stwierdzisz, że to nie działa w przeglądarce.
  • Safari: "Safari"
  • Chrome: "Chrome"
  • Firefox: "Firefox"

Możesz nawet zmodyfikować to, aby uzyskać wersję przeglądarki, jeśli chcesz. Pamiętaj, że istnieją lepsze sposoby na uzyskanie wersji przeglądarki

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+\/[\d.]+/g)[0].split('/')

Przykładowe wyjście:

Firefox/39.0    
 1
Author: Downgoat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-07 22:05:45

Wiem, że jestem za późno na to pytanie, ale pomyślałem, że wrzucę tu swoje fragmenty. Wiele odpowiedzi tutaj jest OK, i, jak ktoś wskazuje, generalnie najlepiej jest użyć feature detection zamiast polegać na userAgent string. Jednakże, jeśli zamierzasz iść tą drogą, napisałem kompletny fragment, a także alternatywną implementację jQuery, która zastąpi przestarzałą $.browser.


Vanilla JS

Mój pierwszy fragment po prostu dodaje cztery właściwości do obiektu navigator: browser, version, mobile, & webkit.

JsFiddle


/** navigator [extended]
 *  Simply extends Browsers navigator Object to include browser name, version number, and mobile type (if available).
 *
 *  @property {String} browser The name of the browser.
 *  @property {Double} version The current Browser version number.
 *  @property {String|Boolean} mobile Will be `false` if is not found to be mobile device. Else, will be best guess Name of Mobile Device (not to be confused with browser name)
 *  @property {Boolean} webkit If is webkit or not.
 */
;(function(){function c(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return"MSIE";case /Chrome/.test(navigator.userAgent):return"Chrome";case /Opera/.test(navigator.userAgent):return"Opera";case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):return/Silk/i.test(navigator.userAgent)?"Silk":"Kindle";case /BlackBerry/.test(navigator.userAgent):return"BlackBerry";case /PlayBook/.test(navigator.userAgent):return"PlayBook";case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):return"Blackberry";
case /Android/.test(navigator.userAgent):return"Android";case /Safari/.test(navigator.userAgent):return"Safari";case /Firefox/.test(navigator.userAgent):return"Mozilla";case /Nokia/.test(navigator.userAgent):return"Nokia"}}catch(a){console.debug("ERROR:setBrowser\t",a)}}function d(){try{switch(!0){case /Sony[^ ]*/i.test(navigator.userAgent):return"Sony";case /RIM Tablet/i.test(navigator.userAgent):return"RIM Tablet";case /BlackBerry/i.test(navigator.userAgent):return"BlackBerry";case /iPhone/i.test(navigator.userAgent):return"iPhone";
case /iPad/i.test(navigator.userAgent):return"iPad";case /iPod/i.test(navigator.userAgent):return"iPod";case /Opera Mini/i.test(navigator.userAgent):return"Opera Mini";case /IEMobile/i.test(navigator.userAgent):return"IEMobile";case /BB[0-9]{1,}; Touch/i.test(navigator.userAgent):return"BlackBerry";case /Nokia/i.test(navigator.userAgent):return"Nokia";case /Android/i.test(navigator.userAgent):return"Android"}}catch(a){console.debug("ERROR:setMobile\t",a)}return!1}function e(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return/Trident/i.test(navigator.userAgent)&&
/rv:([0-9]{1,}[\.0-9]{0,})/.test(navigator.userAgent)?parseFloat(navigator.userAgent.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")):/MSIE/i.test(navigator.userAgent)&&0<parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge";case /Chrome/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Opera/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].replace(/[^0-9\.]/g,
""));case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):if(/Silk/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));if(/Kindle/i.test(navigator.userAgent)&&/Version/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /BlackBerry/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("/")[1].replace(/[^0-9\.]/g,
""));case /PlayBook/.test(navigator.userAgent):case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):case /Safari/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Firefox/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split(/Firefox\//i)[1].replace(/[^0-9\.]/g,""));case /Android/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,
""));case /Nokia/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Browser")[1].replace(/[^0-9\.]/g,""))}}catch(a){console.debug("ERROR:setVersion\t",a)}}a:{try{if(navigator&&navigator.userAgent){navigator.browser=c();navigator.mobile=d();navigator.version=e();var b;b:{try{b=/WebKit/i.test(navigator.userAgent);break b}catch(a){console.debug("ERROR:setWebkit\t",a)}b=void 0}navigator.webkit=b;break a}}catch(a){}throw Error("Browser does not support `navigator` Object |OR| has undefined `userAgent` property.");
}})();
/*  simple c & p of above   */

 1
Author: SpYk3HH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-05 16:34:37

To jest to, czego używam:

var ua = navigator.userAgent;
var info = {
        browser: /Edge\/\d+/.test(ua) ? 'ed' : /MSIE 9/.test(ua) ? 'ie9' : /MSIE 10/.test(ua) ? 'ie10' : /MSIE 11/.test(ua) ? 'ie11' : /MSIE\s\d/.test(ua) ? 'ie?' : /rv\:11/.test(ua) ? 'ie11' : /Firefox\W\d/.test(ua) ? 'ff' : /Chrom(e|ium)\W\d|CriOS\W\d/.test(ua) ? 'gc' : /\bSafari\W\d/.test(ua) ? 'sa' : /\bOpera\W\d/.test(ua) ? 'op' : /\bOPR\W\d/i.test(ua) ? 'op' : typeof MSPointerEvent !== 'undefined' ? 'ie?' : '',
        os: /Windows NT 10/.test(ua) ? "win10" : /Windows NT 6\.0/.test(ua) ? "winvista" : /Windows NT 6\.1/.test(ua) ? "win7" : /Windows NT 6\.\d/.test(ua) ? "win8" : /Windows NT 5\.1/.test(ua) ? "winxp" : /Windows NT [1-5]\./.test(ua) ? "winnt" : /Mac/.test(ua) ? "mac" : /Linux/.test(ua) ? "linux" : /X11/.test(ua) ? "nix" : "",
        touch: 'ontouchstart' in document.documentElement,
        mobile: /IEMobile|Windows Phone|Lumia/i.test(ua) ? 'w' : /iPhone|iP[oa]d/.test(ua) ? 'i' : /Android/.test(ua) ? 'a' : /BlackBerry|PlayBook|BB10/.test(ua) ? 'b' : /Mobile Safari/.test(ua) ? 's' : /webOS|Mobile|Tablet|Opera Mini|\bCrMo\/|Opera Mobi/i.test(ua) ? 1 : 0,
        tablet: /Tablet|iPad/i.test(ua),
};

info właściwości:

  • browser: gc dla Google Chrome; ie9-ie11 dla IE; ie? dla starego lub nieznanego IE; ed Dla Edge; ff dla Firefoksa; sa dla Safari; op dla Opery.
  • os: mac win7 win8 win10 winnt winxp winvista linux nix
  • mobile: a dla Androida; i dla iOS (iPhone iPad); w Dla Windows Phone; b dla Blackberry; s dla niezauważonego telefonu z systemem Safari; 1 dla innych niewykrytych telefonów komórkowych; 0 Dla Nie-telefonów komórkowych
  • touch: true do urządzeń z obsługą dotyku, w tym laptopów/notebooków dotykowych, które mają jednocześnie mysz i dotyk; [31]} bez obsługi dotyku [41]}
  • tablet: true lub false

Https://jsfiddle.net/oriadam/ncb4n882/

 1
Author: oriadam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-11 19:34:07
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;
 1
Author: Juvenik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-27 05:45:11

Nie dokładnie to, czego chcesz, ale blisko tego:

var jscriptVersion = /*@cc_on @if(@_jscript) @_jscript_version @else @*/ false /*@end @*/;
var geckoVersion = navigator.product === 'Gecko' && navigator.productSub;
var operaVersion = 'opera' in window && 'version' in opera && opera.version();

Zmienne będą zawierać odpowiednią wersję lub false, jeśli nie jest ona dostępna.

Byłbym wdzięczny, gdyby ktoś korzystający z Chrome mógł się dowiedzieć, czy można używać window.chrome w podobny sposób jak window.opera.

 0
Author: Christoph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-03-08 13:24:44

Czasami potrzebujemy prostej metody, aby sprawdzić, czy przeglądarka jest IE, czy nie. Tak może być:

 var isMSIE = (/trident/i).test(navigator.userAgent);

 if(isMSIE)
 {
  /* do something for ie */
 }
 else
 {
  /* do something else */
 }

Lub uproszczona metoda siva:

 if(!!navigator.systemLanguage)
 {
  /* do something for ie */
 }
 else
 {
  /* do something else */
 }

MSIE v. 11 sprawdź:

if( (/trident/i).test(navigator.userAgent) && (/rv:/i).test(navigator.userAgent) )
{
  /* do something for ie 11 */
}

Inne przeglądarki IE zawierają łańcuch MSIE we właściwości userAgent i mogą być przez niego przechwytywane.

 0
Author: Christiyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-04 16:17:35

Znalazłem coś ciekawego i szybszego. IE obsługuje navigator.systemLanguage, która zwraca "en-US", gdzie inne przeglądarki zwracają undefined.

<script>
    var lang = navigator.systemLanguage;
    if (lang!='en-US'){document.write("Well, this is not internet explorer");}
    else{document.write("This is internet explorer");}
</script>
 0
Author: siva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-03 21:59:02

Robię tę małą funkcję, mam nadzieję, że pomoże. Tutaj znajdziesz najnowszą wersję browserDetection

function detectBrowser(userAgent){
  var chrome  = /.*(Chrome\/).*(Safari\/).*/g;
  var firefox = /.*(Firefox\/).*/g;
  var safari  = /.*(Version\/).*(Safari\/).*/g;
  var opera   = /.*(Chrome\/).*(Safari\/).*(OPR\/).*/g

  if(opera.exec(userAgent))
    return "Opera"
  if(chrome.exec(userAgent))
    return "Chrome"
  if(safari.exec(userAgent))
    return "Safari"
  if(firefox.exec(userAgent))
    return "Firefox"
}
 0
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-16 17:07:09

Poniżej urywek kodu pokaże jak można wyświetlać elementy UI w zależności od wersji IE i przeglądarki

$(document).ready(function () {

var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {

    //Show UI elements specific to IE version 8 or low

    } else {
    //Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
    }
}
);

Poniżej podamy jak możemy uzyskać wersję IE

function GetMSIieversion() {

var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}

var trident = ua.indexOf('Trident/');
if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}

var edge = ua.indexOf('Edge/');
if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}

// other browser like Chrome,Mozila..etc
return false;

}
 -1
Author: Rinoy Ashokan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-08 12:36:40

Z jQuery:

$.browser

Daje coś w rodzaju:

Object {chrome: true, version: "26.0.1410.63", webkit: true}
 -2
Author: masterweily,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-11 15:08:00