如何使用 jQuery 检测浏览器类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19352522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:45:15  来源:igfitidea点击:

How can I detect browser type using jQuery?

javascriptjqueryinternet-explorerfirefoxbrowser

提问by sealong Maly

I want to detect if the user is using IE and Firefox but I cannot find the script.

我想检测用户是否使用 IE 和 Firefox,但我找不到脚本。

I have code as below:

我有如下代码:

$(document).ready(function(e) {
    $.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()); 
    if($.browser.chrome){
        alert(1);
             //this work well
    }
            else if(//the browser is IE){alert(2);}
            else if(//the browser is Firefox){alert(3);}

   //The problem is that I don't know how to write a script for IE and FireFox browser for chrome is work fine
 )};

回答by Milosz

The best solution is probably: use Modernizr.

最好的解决方案可能是:使用 Modernizr。

However, if you necessarily want to use $.browser property, you can do it using jQuery Migrateplugin (for JQuery >= 1.9 - in earlier versions you can just use it) and then do something like:

但是,如果您一定要使用 $.browser 属性,您可以使用jQuery Migrate插件(对于 JQuery >= 1.9 - 在早期版本中您可以使用它),然后执行以下操作:

if($.browser.chrome) {
   alert(1);
} else if ($.browser.mozilla) {
   alert(2);
} else if ($.browser.msie) {
   alert(3);
}

And if you need for some reason to use navigator.userAgent, then it would be:

如果您出于某种原因需要使用 navigator.userAgent,那么它将是:

$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase()); 
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase()); 

回答by András

My solution for iedetection:

我的检测解决方案:

if (navigator.userAgent.match(/msie/i) || navigator.userAgent.match(/trident/i) ){
    $("html").addClass("ie");
}

Jquery needed.

需要jQuery。

回答by xxbbcc

You shouldn't write your own browser-detection code - it's been done many times before. Use Modernizrto detect independent browser features instead. It's better to detect the various features than to detect entire browsers because various browsers may support different set of features and those features may even change through various versions of the same browser. If you detect the presence of a given feature, your code will likely work better in more browsers. This is especially true for the various mobile browsers.

您不应该编写自己的浏览器检测代码 - 以前已经做过很多次了。使用Modernizr来检测独立的浏览器功能。检测各种功能比检测整个浏览器要好,因为不同的浏览器可能支持不同的功能集,而这些功能甚至可能会随着同一浏览器的不同版本而改变。如果您检测到给定功能的存在,您的代码可能会在更多浏览器中运行得更好。对于各种移动浏览器来说尤其如此。

When you run Modernizr, it'll update your HEADelement's classattribute so that it lists the various features of the browser that you're using - you can then use Javascript to query the attribute and decide what to do if a feature is present (or missing).

当您运行 Modernizr 时,它会更新您HEAD元素的class属性,以便它列出您正在使用的浏览器的各种功能 - 然后您可以使用 Javascript 查询该属性并决定如果某个功能存在(或缺失)该怎么办)。

回答by EpokK

Use this:

用这个:

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], function ($) {
      return factory($);
    });
  } else if (typeof module === 'object' && typeof module.exports === 'object') {
    // Node-like environment
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(window.jQuery);
  }
}(function(jQuery) {
  "use strict";

  function uaMatch( ua ) {
    // If an UA is not provided, default to the current browser UA.
    if ( ua === undefined ) {
      ua = window.navigator.userAgent;
    }
    ua = ua.toLowerCase();

    var match = /(edge)\/([\w.]+)/.exec( ua ) ||
        /(opr)[\/]([\w.]+)/.exec( ua ) ||
        /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

    var platform_match = /(ipad)/.exec( ua ) ||
        /(ipod)/.exec( ua ) ||
        /(iphone)/.exec( ua ) ||
        /(kindle)/.exec( ua ) ||
        /(silk)/.exec( ua ) ||
        /(android)/.exec( ua ) ||
        /(windows phone)/.exec( ua ) ||
        /(win)/.exec( ua ) ||
        /(mac)/.exec( ua ) ||
        /(linux)/.exec( ua ) ||
        /(cros)/.exec( ua ) ||
        /(playbook)/.exec( ua ) ||
        /(bb)/.exec( ua ) ||
        /(blackberry)/.exec( ua ) ||
        [];

    var browser = {},
        matched = {
          browser: match[ 5 ] || match[ 3 ] || match[ 1 ] || "",
          version: match[ 2 ] || match[ 4 ] || "0",
          versionNumber: match[ 4 ] || match[ 2 ] || "0",
          platform: platform_match[ 0 ] || ""
        };

    if ( matched.browser ) {
      browser[ matched.browser ] = true;
      browser.version = matched.version;
      browser.versionNumber = parseInt(matched.versionNumber, 10);
    }

    if ( matched.platform ) {
      browser[ matched.platform ] = true;
    }

    // These are all considered mobile platforms, meaning they run a mobile browser
    if ( browser.android || browser.bb || browser.blackberry || browser.ipad || browser.iphone ||
      browser.ipod || browser.kindle || browser.playbook || browser.silk || browser[ "windows phone" ]) {
      browser.mobile = true;
    }

    // These are all considered desktop platforms, meaning they run a desktop browser
    if ( browser.cros || browser.mac || browser.linux || browser.win ) {
      browser.desktop = true;
    }

    // Chrome, Opera 15+ and Safari are webkit based browsers
    if ( browser.chrome || browser.opr || browser.safari ) {
      browser.webkit = true;
    }

    // IE11 has a new token so we will assign it msie to avoid breaking changes
    // IE12 disguises itself as Chrome, but adds a new Edge token.
    if ( browser.rv || browser.edge ) {
      var ie = "msie";

      matched.browser = ie;
      browser[ie] = true;
    }

    // Blackberry browsers are marked as Safari on BlackBerry
    if ( browser.safari && browser.blackberry ) {
      var blackberry = "blackberry";

      matched.browser = blackberry;
      browser[blackberry] = true;
    }

    // Playbook browsers are marked as Safari on Playbook
    if ( browser.safari && browser.playbook ) {
      var playbook = "playbook";

      matched.browser = playbook;
      browser[playbook] = true;
    }

    // BB10 is a newer OS version of BlackBerry
    if ( browser.bb ) {
      var bb = "blackberry";

      matched.browser = bb;
      browser[bb] = true;
    }

    // Opera 15+ are identified as opr
    if ( browser.opr ) {
      var opera = "opera";

      matched.browser = opera;
      browser[opera] = true;
    }

    // Stock Android browsers are marked as Safari on Android.
    if ( browser.safari && browser.android ) {
      var android = "android";

      matched.browser = android;
      browser[android] = true;
    }

    // Kindle browsers are marked as Safari on Kindle
    if ( browser.safari && browser.kindle ) {
      var kindle = "kindle";

      matched.browser = kindle;
      browser[kindle] = true;
    }

     // Kindle Silk browsers are marked as Safari on Kindle
    if ( browser.safari && browser.silk ) {
      var silk = "silk";

      matched.browser = silk;
      browser[silk] = true;
    }

    // Assign the name and platform variable
    browser.name = matched.browser;
    browser.platform = matched.platform;
    return browser;
  }

  // Run the matching process, also assign the function to the returned object
  // for manual, jQuery-free use if desired
  window.jQBrowser = uaMatch( window.navigator.userAgent );
  window.jQBrowser.uaMatch = uaMatch;

  // Only assign to jQuery.browser if jQuery is loaded
  if ( jQuery ) {
    jQuery.browser = window.jQBrowser;
  }

  return window.jQBrowser;
}));

回答by arvinda kumar

You can use this code to find correct browser and you can make changes for any target browser.....

您可以使用此代码找到正确的浏览器,并且可以对任何目标浏览器进行更改.....

function myFunction() { 
        if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ){
            alert('Opera');
        }
        else if(navigator.userAgent.indexOf("Chrome") != -1 ){
            alert('Chrome');
        }
        else if(navigator.userAgent.indexOf("Safari") != -1){
            alert('Safari');
        }
        else if(navigator.userAgent.indexOf("Firefox") != -1 ){
             alert('Firefox');
        }
        else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){
          alert('IE'); 
        }  
        else{
           alert('unknown');
        }
    }
<!DOCTYPE html>
<html>
<head>
 <title>Browser detector</title>

</head>
<body onload="myFunction()">
// your code here 
</body>
</html>

回答by cyberoot

Try to use it

尝试使用它

$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){ 
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});

回答by sandeep kumar

You can get Browser type here:

您可以在此处获取浏览器类型:

<script>
    var browser_type = Object.keys($.browser)[0];
    alert(browser_type);
</script>

回答by arvinda kumar

$(document).ready(function(){
    alert('sdfsd');
    checkOperatingSystem();
   });
   function checkOperatingSystem(){
       var  userAgent = navigator.userAgent || navigator.vendor || window.opera;

       
       if (/android/i.test(userAgent)) {
           alert('android');
       }

       
       if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
           alert('ios');
       }

      
       if (navigator.appVersion.indexOf("Win")!=-1)
       {
           
       }

      
       if (navigator.appVersion.indexOf("Mac")!=-1)
       {
           
       }  
   }

回答by Prem Kumar

Another way to find versions of IE

另一种查找IE版本的方法

http://tanalin.com/en/articles/ie-version-js/

http://tanalin.com/en/articles/ie-version-js/

IE versions Condition to check for

IE 版本检查条件

IE 10 or older -   document.all <BR/> 
IE 9 or older  -   document.all && !window.atob <br/>
IE 8 or older  -   document.all && !document.addEventListener <br/>
IE 7 or older  -   document.all && !document.querySelector <br/>
IE 6 or older  -   document.all && !window.XMLHttpRequest <br/>
IE 5.x         -   document.all && !document.compatMode

回答by Vishal Thakur

$.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()); 

if($.browser.chrome){
  alert(1);      
}

UPDATE:(10x to @Mr. Bacciagalupe)

更新:(10 倍于@Bacciagalupe 先生)

jQuery has removed $.browserfrom 1.9and their latest release.

jQuery的已删除$.browser1.9和他们的最新版本。

But you can still use $.browser as a standalone plugin, found here

但是你仍然可以使用 $.browser 作为一个独立的插件,在这里找到