[removed] How to find out if the user browser is Chrome?

后端 未结 15 1563
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 09:41

I need some function returning a boolean value to check if the browser is Chrome.

How do I create such functionality?

15条回答
  •  灰色年华
    2020-11-22 10:22

    To know the names of different desktop browsers (Firefox, IE, Opera, Edge, Chrome). Except Safari.

    function getBrowserName() {
      var browserName = '';
      var userAgent = navigator.userAgent;
      (typeof InstallTrigger !== 'undefined') && (browserName = 'Firefox');
      ( /* @cc_on!@*/ false || !!document.documentMode) && (browserName = 'IE');
      (!!window.chrome && userAgent.match(/OPR/)) && (browserName = 'Opera');
      (!!window.chrome && userAgent.match(/Edge/)) && (browserName = 'Edge');
      (!!window.chrome && !userAgent.match(/(OPR|Edge)/)) && (browserName = 'Chrome');
    
      /**
       * Expected returns
       * Firefox, Opera, Edge, Chrome
       */
      return browserName;
    }
    

    Works in the following browser versions:

    Opera - 58.0.3135.79
    Firefox - 65.0.2 (64-bit)
    IE - 11.413.15063 (JS Fiddle no longer supports IE just paste in Console)
    Edge - 44.17763.1.0
    Chrome - 72.0.3626.121 (Official Build) (64-bit)
    

    View the gist here and the fiddle here

    The original code snippet no longer worked for Chrome and I forgot where I found it. It had safari before but I no longer have access to safari so I cannot verify anymore.

    Only the Firefox and IE codes were part of the original snippet.

    The checking for Opera, Edge, and Chrome is straight forward. They have differences in the userAgent. OPR only exists in Opera. Edge only exists in Edge. So to check for Chrome these string shouldn't be there.

    As for the Firefox and IE, I cannot explain what they do.

    I'll be adding this functionality to a package i'm writing

提交回复
热议问题