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

24

我希望检测用户是否在使用IE和Firefox浏览器,但我找不到相应的脚本。

我的代码如下:

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

如果您依赖于 $.browser,那么您肯定不需要在代码中实现浏览器检测。无论哪种情况,都应考虑改用特性检测。 - WynandB
1
如上所述并在 https://api.jquery.com/jquery.browser/ 中提到,“此属性已在 jQuery 1.9 中删除,仅通过 jQuery.migrate 插件可用。请尝试改用特性检测。” - Meetai.com
11个回答

29

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

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

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

如果出于某种原因需要使用navigator.userAgent,则应为:

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

现代浏览器检测工具Modernizr和jQuery Migrate插件是否可以在任何浏览器中使用,比如IE6甚至更早的浏览器,因为这是我们使用浏览器检测的主要目的之一。请您给予建议。 - 夏期劇場
13
$.browser已经从所有jQuery 1.9+版本中移除,该版本于2013年01月15日发布。 - Bryce Siedschlaw
我在IE 11中遇到了这个问题:“无法获取未定义或空引用的'mozilla'属性”。 - eaglei22
这意味着要依赖于jQuery迁移插件。您必须保留插件以使代码正常工作。我不确定让您的代码依赖于jQuery迁移实用程序是否是一个好习惯。总的来说,我认为它的主要目的是帮助您将代码升级到较新版本的jQuery,而不是在您使用现代版本的jQuery时使旧版代码正常工作。我认为一般情况下,程序员应避免在迁移jQuery到较新版本的项目范围之外使用jQuery迁移。升级完成后,应删除jQuery迁移。 - Jaime Montoya

29

我对于 ie 浏览器的检测解决方案:

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

需要 Jquery。


这可以通过检测所有的msIE浏览器版本来实现。你有没有一个方便的变体来仅检测IE8和IE9,而不检测IE7、IE10或IE11? - j4v1
提供的答案需要在HTML中添加内容,这并不是我真正考虑的。不过我找到了另一篇文章:http://tanalin.com/en/articles/ie-version-js/ - j4v1
1
这个答案最好。我不必担心使用插件,而且似乎大多数情况下IE会出问题。所以最好检查IE浏览器并相应处理。有趣的是,在我的某个案例中,我需要为IE设置margin-left 32%,而FF则是margin-left -16%。 - eaglei22

11

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

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>


这是一个很棒的答案。 - yose
这会在Microsoft Edge上引发“Chrome”错误,因此不准确。 - Pedro Joaquín

7
你不应该编写自己的浏览器检测代码——这已经被做过很多次了。相反地,使用Modernizr来检测独立的浏览器特性。检测各种特性比检测整个浏览器更好,因为各种浏览器可能支持不同的特性,并且这些特性甚至可能在同一浏览器的不同版本中发生变化。如果你检测到了某个特定特性的存在,你的代码在更多的浏览器中可能会更好地工作,这在各种移动浏览器中尤其如此。

当你运行Modernizr时,它会更新你的HEAD元素的class属性,以列出你正在使用的浏览器的各种特性——然后你可以使用Javascript查询属性并决定如果一个特性存在(或不存在)要做什么。


5
请使用以下内容:
(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;
}));

1

尝试使用它

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

你测试用什么浏览器 @Techy - cyberoot
Chrome OS,我也在Fiddle中检查了这段代码。 - Techy
7
这句话已经被重复说了无数遍,但是$.browser已经从所有的jQuery版本1.9+中移除了,该版本于2013年01月15日发布。 - Bryce Siedschlaw

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

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

更新:(感谢 @Mr. Bacciagalupe)

jQuery 已经在最新版本中删除了 $.browser,包括 1.9 版本。

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


0

寻找IE版本的另一种方法

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

检查的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

0

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

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

0

$(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)
       {
           
       }  
   }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接