【问题标题】:How can I detect browser type using jQuery?如何使用 jQuery 检测浏览器类型?
【发布时间】:2013-10-21 13:31:10
【问题描述】:

我想检测用户是否在使用 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,那么肯定不需要在你的代码中实现浏览器检测。无论哪种情况,请考虑改用特征检测。
  • 如上所述和api.jquery.com/jquery.browser,“此属性已在 jQuery 1.9 中删除,仅可通过 jQuery.migrate 插件使用。请尝试改用特征检测。”

标签: javascript jquery internet-explorer firefox browser


【解决方案1】:

最好的解决方案可能是:使用 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 甚至更旧的浏览器,因为这是我们使用浏览器检测的主要目的之一。请提出建议。
  • $.browser 已从 2013-01-15 发布的所有 jQuery 版本 1.9+ 中删除。
  • 我在 IE 11 中得到了这个,“无法获取未定义或空引用的属性 'mozilla'”
  • 这意味着依赖 jQuery 迁移插件。您必须保留插件才能使代码正常工作。我不确定让您的代码依赖于 jQuery 迁移实用程序是一个好习惯。总的来说,我认为它的主要目的是或者应该是帮助您将代码升级到更新版本的 jQuery,而不是在您使用现代版本的 jQuery 时让您的遗留代码工作。我认为一般程序员应该避免在将 jQuery 迁移到更新版本的项目范围之外使用 jQuery 迁移。升级完成后,应删除 jQuery migrate。
【解决方案2】:

我的ie检测解决方案:

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

需要 Jquery。

【讨论】:

  • 这通过检测所有 msIE 浏览器版本来工作。您是否有一个方便的变体来检测,比如 IE8 和 IE9,而不是 IE7、IE10 或 IE11?
  • 提供的答案需要在 html 中添加内容,我并没有真正考虑过。我确实找到了另一篇文章:tanalin.com/en/articles/ie-version-js
  • 这个答案效果最好。我不必担心使用插件,而且似乎大部分时间 IE 都有问题。所以我最好检查一下 IE 浏览器并进行相应的处理。有趣的是,在我的一个案例中,我需要为 IE 保留 32% 的边距,而 FF 的边距为 -16% ..
【解决方案3】:

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

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>

【讨论】:

  • 这个答案很好
【解决方案4】:

您不应该编写自己的浏览器检测代码 - 以前已经做过很多次了。请改用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;
    }));
    

    【讨论】:

      【解决方案6】:

      尝试使用它

      $(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
      • chrome os,我也检查了小提琴里面的这段代码。
      • 之前已经说过一百万次了,但是 $.browser 已从 2013-01-15 发布的所有 jQuery 版本 1.9+ 中删除
      【解决方案7】:

      另一种查找 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
      

      【讨论】:

        【解决方案8】:
        $.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase()); 
        
        if($.browser.chrome){
          alert(1);      
        }
        

        更新:(10x 到 @Mr. Bacciagalupe)

        jQuery 已从 1.9 及其最新版本中删除了 $.browser

        但你仍然可以将 $.browser 作为独立插件使用,发现 here

        【讨论】:

          【解决方案9】:

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

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

          【讨论】:

            【解决方案10】:

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

            【讨论】:

              【解决方案11】:

              我用过这个,它对我有用。还包括 jquery migrate 插件和 jquery 文件。

              if ( $.browser.webkit ) {
              alert( "This is WebKit!" );
              }
              

              【讨论】:

                猜你喜欢
                • 2017-02-09
                • 1970-01-01
                • 2011-09-26
                • 2021-11-21
                • 2013-12-15
                • 2011-11-12
                • 1970-01-01
                • 2011-02-09
                • 2011-01-30
                相关资源
                最近更新 更多