Jak można wykryć wersję przeglądarki?

Szukałem kodu, który pozwoliłby mi wykryć, czy Użytkownik odwiedzający stronę Ma Firefoksa 3 lub 4. Wszystko, co znalazłem, to kod do wykrywania typu przeglądarki, ale NIE wersji.

Jak mogę wykryć taką wersję przeglądarki?

Author: Brad Larson, 2011-05-07

23 answers

Możesz zobaczyć, co mówi przeglądarka i użyć tych informacji do rejestrowania lub testowania wielu przeglądarek.

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(' ');
})();

console.log(navigator.sayswho); // outputs: `Chrome 62`
 433
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
2018-02-22 12:31:14

To jest poprawa w odpowiedzi Kennebec.

function get_browser() {
    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:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bOPR|Edge\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[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: M[1]
    };
 }

A potem po prostu biegniesz:

var browser=get_browser();
// browser.name = 'Chrome'
// browser.version = '40'
W ten sposób możesz się uchronić przed mrokiem Kodeksu.
 191
Author: Hermann Ingjaldsson,
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-11-24 10:24:59

To łączy odpowiedź kennebca (K) z odpowiedzią Hermanna Ingjaldssona (H):

  • zachowuje minimalny kod oryginalnej odpowiedzi. (K)
  • [[4]}współpracuje z Microsoft Edge (K)
  • rozszerza obiekt nawigatora zamiast tworzyć nową zmienną / obiekt. (K)
  • oddziela wersję przeglądarki i nazwę na niezależne obiekty potomne. H)

 

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

console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }

if (navigator.browserSpecs.name == 'Firefox') {
    // Do something for Firefox.
    if (navigator.browserSpecs.version > 42) {
        // Do something for Firefox versions greater than 42.
    }
}
else {
    // Do something for all other browsers.
}
 34
Author: Brandon,
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
2018-04-25 17:10:37

Użyj tego: http://www.quirksmode.org/js/detect.html

alert(BrowserDetect.browser); // will say "Firefox"
alert(BrowserDetect.version); // will say "3" or "4"
 18
Author: Oliver Moran,
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
2011-05-06 21:01:06

Biblioteka bowser JavaScript oferuje tę funkcjonalność.

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
}
Wydaje się być dobrze utrzymana.
 18
Author: Michael Cole,
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-11-03 15:13:34

Szukałem rozwiązania dla siebie, ponieważ jQuery 1.9.1 i wyżej usunęły funkcjonalność $.browser. Wymyśliłem taką małą funkcję, która mi odpowiada. Potrzebuje zmiennej globalnej (nazwałem moją _browser), aby sprawdzić, która to przeglądarka. Napisałem jsfiddle , aby zilustrować, jak można go używać, oczywiście można go rozszerzyć dla innych przeglądarek po prostu dodając test dla _browser.foo, gdzie foo to nazwa przeglądarki. Zrobiłem tylko popularne jeden.

DetectBrowser()

_browser = {};

function detectBrowser() {
  var uagent = navigator.userAgent.toLowerCase(),
      match = '';

  _browser.chrome  = /webkit/.test(uagent)  && /chrome/.test(uagent)      &&
                     !/edge/.test(uagent);

  _browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);

  _browser.msie    = /msie/.test(uagent)    || /trident/.test(uagent)     ||
                     /edge/.test(uagent);

  _browser.safari  = /safari/.test(uagent)  && /applewebkit/.test(uagent) &&
                     !/chrome/.test(uagent);

  _browser.opr     = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
                     /chrome/.test(uagent)  && /safari/.test(uagent)      &&
                     /opr/.test(uagent);

  _browser.version = '';

  for (x in _browser) {
    if (_browser[x]) {

      match = uagent.match(
                new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
              );

      if (match) {
        _browser.version = match[3];
      } else {
        match = uagent.match(new RegExp("rv:([0-9]+)"));
        _browser.version = match ? match[1] : "";
      }
      break;
    }
  }
  _browser.opera = _browser.opr;
  delete _browser.opr;
}

Aby sprawdzić, czy aktualną przeglądarką jest Opera, wykonaj

if (_browser.opera) { // Opera specific code }

Edit Poprawiono formatowanie, Naprawiono wykrywanie IE11 i Opera / Chrome, zmieniono browserResult z wyniku. Teraz kolejność klawiszy _browser nie ma znaczenia. Aktualizacja jsfiddle link.

2015/08/11 Edycja dodano nowy testcase dla Internet Explorer 12( EDGE), Naprawiono mały problem z wyrażeniem regexp. Aktualizacja jsFiddle link.

 16
Author: Danail Gabenski,
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-11 21:07:48

JQuery poradzi sobie z tym całkiem nieźle (jQuery.przeglądarka )

var ua = $.browser;
if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
    alert( "Do stuff for firefox 3" );
}

EDIT: jak napisał Joshua w komentarzu poniżej, jQuery.właściwość browser nie jest już obsługiwana w jQuery od wersji 1.9(przeczytaj jQuery 1.9 release notes aby uzyskać więcej szczegółów). jQuery development team zaleca stosowanie bardziej kompletnego podejścia, takiego jak adaptacja interfejsu użytkownika z Modernizr biblioteka.

 9
Author: Marek,
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-01-16 08:34:12
function BrowserCheck()
{
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\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;
}

Zwróci tablicę, pierwszy element to nazwa przeglądarki, drugi element to Pełny Numer wersji w formacie string.

 9
Author: Michael Bleidistel,
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-04 18:13:12

Oto kilka znanych bibliotek obsługujących wykrywanie przeglądarek.

Bowser by lancedikson-2,713★s-Ostatnia aktualizacja sie 2, 2018-2.6 KB

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

Peron.js by bestiejs-2,059★s-Ostatnia aktualizacja Jul 3, 2018 - 5.7 KB

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>

Wykryj.js by darcyclarke - 509★s - Ostatnia aktualizacja Oct 26, 2015-2.9 KB

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>

JQuery Przeglądarka by gabceb - 485★s - Ostatnia aktualizacja Nov 23, 2015-1.3 KB

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>

Browser Detect (archiwum) by QuirksMode-Ostatnia aktualizacja 14 listopada 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>

Godne Uwagi Wzmianki:

  • Whatbrowser - 1,230★s - Ostatnia aktualizacja 05 lutego 2018
  • Modernizr - 22,320★s-Ostatnia aktualizacja Mar 4, 2018 - aby pokonać martwego konia, wykrywanie funkcji powinno prowadzić dowolny canIuse style pytania. Wykrywanie przeglądarki jest naprawdę tylko dla miłych gości.

Czytaj Dalej

 8
Author: KyleMit,
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
2018-08-03 12:12:38

W czystym Javascript możesz dopasować Wyrażenie regularne na navigator.userAgent, aby znaleźć wersję Firefoksa:

var uMatch = navigator.userAgent.match(/Firefox\/(.*)$/),
    ffVersion;
if (uMatch && uMatch.length > 1) {
    ffVersion = uMatch[1];
}

ffVersion będzie undefined, Jeśli nie przeglądarką Firefox.

Zobacz przykład pracy →

 7
Author: mVChr,
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
2011-05-06 21:00:15

Spójrz na navigator.userAgent - Firefox/xxx.xxx.xxx jest podany na końcu.

 4
Author: Ry-,
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
2011-05-06 20:55:43
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera, the true version is after "Opera" or after "Version"

if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent

else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"

else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"

else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"

else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent

else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
          (verOffset=nAgt.lastIndexOf('/')) )
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}

// trim the fullVersion string at semicolon/space if present

if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion);
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

Zobacz demo tutaj.. http://jsfiddle.net/hw4jM/3/

 3
Author: newTag,
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-02-10 05:35:22

Napisałem detektor wersji oparty na odpowiedzi Hermanna Ingjaldssona, ale bardziej solidny i zwracający obiekt z nazwą / danymi wersji. Obejmuje główne przeglądarki, ale nie przejmuję się mnóstwem mobilnych i mniejszych: {]}

function getBrowserData(nav) {
    var data = {};

    var ua = data.uaString = nav.userAgent;
    var browserMatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
    if (browserMatch[1]) { browserMatch[1] = browserMatch[1].toLowerCase(); }
    var operaMatch = browserMatch[1] === 'chrome';
    if (operaMatch) { operaMatch = ua.match(/\bOPR\/([\d\.]+)/); }

    if (/trident/i.test(browserMatch[1])) {
        var msieMatch = /\brv[ :]+([\d\.]+)/g.exec(ua) || [];
        data.name = 'msie';
        data.version = msieMatch[1];
    }
    else if (operaMatch) {
        data.name = 'opera';
        data.version = operaMatch[1];
    }
    else if (browserMatch[1] === 'safari') {
        var safariVersionMatch = ua.match(/version\/([\d\.]+)/i);
        data.name = 'safari';
        data.version = safariVersionMatch[1];
    }
    else {
        data.name = browserMatch[1];
        data.version = browserMatch[2];
    }

    var versionParts = [];
    if (data.version) {
        var versionPartsMatch = data.version.match(/(\d+)/g) || [];
        for (var i=0; i < versionPartsMatch.length; i++) {
            versionParts.push(versionPartsMatch[i]);
        }
        if (versionParts.length > 0) { data.majorVersion = versionParts[0]; }
    }
    data.name = data.name || '(unknown browser name)';
    data.version = {
        full: data.version || '(unknown full browser version)',
        parts: versionParts,
        major: versionParts.length > 0 ? versionParts[0] : '(unknown major browser version)'
    };

    return data;
};

Można go użyć w następujący sposób:

var brData = getBrowserData(window.navigator || navigator);
console.log('name: ' + brData.name);
console.log('major version: ' + brData.version.major);
// etc.
 3
Author: Jez,
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-16 17:14:06
<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>
 2
Author: WEFX,
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
2011-05-06 20:56:34

Zrobiłem skrypt w kodzie ASP do wykrywania przeglądarki, wersji przeglądarki, systemu operacyjnego i wersji systemu operacyjnego. Powodem, dla którego zrobiłem to w ASP, było to, że chcę przechowywać dane w bazie danych. Więc musiałem wykryć serwer przeglądarki.

Oto kod:

on error resume next
ua = lcase(Request.ServerVariables("HTTP_USER_AGENT"))
moz = instr(ua,"mozilla")  
ffx = instr(ua,"firefox")  
saf = instr(ua,"safari")
crm = instr(ua,"chrome") 
max = instr(ua,"maxthon") 
opr = instr(ua,"opera")
ie4 = instr(ua,"msie 4") 
ie5 = instr(ua,"msie 5") 
ie6 = instr(ua,"msie 6") 
ie7 = instr(ua,"msie 7") 
ie8 = instr(ua,"trident/4.0")
ie9 = instr(ua,"trident/5.0")

if moz>0 then 
    BrowserType = "Mozilla"
    BrVer = mid(ua,moz+8,(instr(moz,ua," ")-(moz+8)))
end if
if ffx>0 then 
    BrowserType = "FireFox"
    BrVer = mid(ua,ffx+8)
end if
if saf>0 then 
    BrowserType = "Safari"
    BrVerPlass = instr(ua,"version")
    BrVer = mid(ua,BrVerPlass+8,(instr(BrVerPlass,ua," ")-(BrVerPlass+8)))
end if
if crm>0 then 
    BrowserType = "Chrome"
    BrVer = mid(ua,crm+7,(instr(crm,ua," ")-(crm+7)))
end if
if max>0 then 
    BrowserType = "Maxthon"
    BrVer = mid(ua,max+8,(instr(max,ua," ")-(max+8)))
end if
if opr>0 then 
    BrowserType = "Opera"
    BrVerPlass = instr(ua,"presto")
    BrVer = mid(ua,BrVerPlass+7,(instr(BrVerPlass,ua," ")-(BrVerPlass+7)))
end if
if ie4>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "4"
end if
if ie5>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "5"
end if
if ie6>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "6"
end if
if ie7>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "7"
end if
if ie8>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "8"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
end if
if ie9>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "9"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
    if ie8>0 then BrVer = BrVer & " (in IE8 compability mode)"
end if

OSSel = mid(ua,instr(ua,"(")+1,(instr(ua,";")-instr(ua,"("))-1)
OSver = mid(ua,instr(ua,";")+1,(instr(ua,")")-instr(ua,";"))-1)

if BrowserType = "Internet Explorer" then
    OSStart = instr(ua,";")
    OSStart = instr(OSStart+1,ua,";")        
    OSStopp = instr(OSStart+1,ua,";")
    OSsel = mid(ua,OSStart+2,(OSStopp-OSStart)-2)
end if

    Select case OSsel
        case "windows nt 6.1"
            OS = "Windows"
            OSver = "7"
        case "windows nt 6.0"
            OS = "Windows"
            OSver = "Vista"
        case "windows nt 5.2"
            OS = "Windows"
            OSver = "Srv 2003 / XP x64"
        case "windows nt 5.1"
            OS = "Windows"
            OSver = "XP"
        case else
            OS = OSSel
    End select

Response.write "<br>" & ua & "<br>" & BrowserType & "<br>" & BrVer & "<br>" & OS & "<br>" & OSver & "<br>"

'Use the variables here for whatever you need........
 2
Author: Pål Sølvberg,
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-02-15 22:21:50

Ta strona wydaje się mieć całkiem ładny fragment, który używa tylko właściwości appString i appVersion w ostateczności, ponieważ twierdzi, że są niewiarygodne w niektórych przeglądarkach. Kod na stronie jest następujący:

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion); 
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
          (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)
 2
Author: Chazmus,
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-05-09 08:35:21

Dodanie własnej implementacji odpowiedzi Hermanna. Potrzebowałem wykrywania systemu operacyjnego, więc to zostało dodane. Zawiera również kod ES6 (ponieważ mamy transpiler), który może być potrzebny do 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;
}

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

 2
Author: relic,
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-01 23:56:00
var ua = navigator.userAgent;

if (/Firefox\//.test(ua))
   var Firefox = /Firefox\/([0-9\.A-z]+)/.exec(ua)[1];
 0
Author: McKayla,
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
2011-05-06 21:04:04

Oto wersja java dla niektórych, którzy chcieliby to zrobić po stronie serwera używając ciągu zwracanego przez HttpServletRequest.getHeader("User-Agent");

Działa na 70 różnych konfiguracjach przeglądarki, których użyłem do testowania.

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
Author: RenaudBlue,
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-01-14 16:13:33

Napisałem to dla moich potrzeb.

Pobiera informacje, takie jak czy jest urządzeniem mobilnym lub czy ma wyświetlacz siatkówki

Try it

var nav = {
        isMobile:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) != null);
        },
        isDesktop:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) == null);
        },
        isAndroid: function() {
            return navigator.userAgent.match(/Android/i);
        },
        isBlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        isIOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        isOpera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        isWindows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        isRetina:function(){
            return window.devicePixelRatio && window.devicePixelRatio > 1;
        },
        isIPad:function(){
            isIPad = (/ipad/gi).test(navigator.platform);
            return isIPad;
        },
        isLandscape:function(){
            if(window.innerHeight < window.innerWidth){
                return true;
            }
            return false;
        },
        getIOSVersion:function(){
            if(this.isIOS()){
                var OSVersion = navigator.appVersion.match(/OS (\d+_\d+)/i);
                OSVersion = OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
                return OSVersion;
            }
            else
                return false;
        },
        isStandAlone:function(){
            if(_.is(navigator.standalone))
                return navigator.standalone;
            return false;
        },
        isChrome:function(){
            var isChrome = (/Chrome/gi).test(navigator.appVersion);
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            return isChrome && isSafari;
        },
        isSafari:function(){
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            var isChrome = (/Chrome/gi).test(navigator.appVersion)
            return !isChrome && isSafari;
        }
}
 0
Author: Marconi,
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-03-04 16:33:31

Używam tego, aby uzyskać nazwę de i numer (int) wersji rzeczywistej przeglądarki:

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

Dla mnie.
 0
Author: Fabian Montoya,
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
2018-03-22 16:52:27

Chcę podzielić się tym kodem, który napisałem dla problemu, który musiałem rozwiązać. Został przetestowany w większości głównych przeglądarek i działa jak urok, dla mnie!

Może się wydawać, że ten kod jest bardzo podobny do innych odpowiedzi, ale zmodyfikował się tak, że mogę go użyć w obiekcie przeglądarki w jquery, który mi ostatnio brakowało, oczywiście jest to kombinacja z powyższych kodów, z niewielkimi ulepszeniami z mojej strony zrobiłem: {]}

(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])
}

})(!!jQuery? jQuery : window.$, navigator.userAgent);

 console.log($.browser.name, $.browser.version, $.browser.msie); 
// if IE 11 output is: IE 11 true
 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
2018-06-18 14:24:12
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset = nAgt.indexOf("OPR/")) != -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset = nAgt.indexOf("Opera")) != -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 6);
    if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
    browserName = "Microsoft Internet Explorer";
    fullVersion = nAgt.substring(verOffset + 5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
    browserName = "Google Chrome";
    fullVersion = nAgt.substring(verOffset + 7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
    browserName = "Safari";
    fullVersion = nAgt.substring(verOffset + 7);
    if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
    browserName = "Mozilla Firefox";
    fullVersion = nAgt.substring(verOffset + 8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
    browserName = nAgt.substring(nameOffset, verOffset);
    fullVersion = nAgt.substring(verOffset + 1);
    if (browserName.toLowerCase() == browserName.toUpperCase()) {
        browserName = navigator.appName;
    }
}
// trim the fullVersion string at semicolon/space if present
if ((ix = fullVersion.indexOf(';')) != -1) fullVersion = fullVersion.substring(0, ix);
if ((ix = fullVersion.indexOf(' ')) != -1) fullVersion = fullVersion.substring(0, ix);

majorVersion = parseInt('' + fullVersion, 10);
if (isNaN(majorVersion)) {
    fullVersion = '' + parseFloat(navigator.appVersion);
    majorVersion = parseInt(navigator.appVersion, 10);
}
 -1
Author: Rajesh Britto,
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-01-30 10:11:23