代码之家  ›  专栏  ›  技术社区  ›  Moaaz Bhnas

如何使用javascript检测不受欢迎的浏览器(百度)?

  •  3
  • Moaaz Bhnas  · 技术社区  · 6 年前

    我试图让我的应用程序跨浏览器提供两种样式,一种用于支持CSS 3D动画的浏览器,另一种用于不支持的浏览器,使用此代码功能检测:

    // Function from: https://stackoverflow.com/a/36191841/7982963
    const isValueSupported = (prop, value) => {
      const el = document.createElement('div');
      el.style[prop] = value;
      return el.style[prop] === value;
    }
    // [unction from: http://lea.verou.me/2009/02/check-if-a-css-property-is-supported/
    const isPropertySupported = property =>  property in document.body.style;
    
    // Detection style inspired by Modernizr library
    if (isValueSupported('perspective', '400px') && isValueSupported('transform-style', 'preserve-3d') && isValueSupported('backface-visibility', 'hidden') && isValueSupported('transform', 'rotateY(-180deg)') && isPropertySupported('perspective') && isPropertySupported('transform-style') && isPropertySupported('backface-visibility') && isPropertySupported('transform') && (!navigator.userAgent.includes('Firefox'))) {
      document.documentElement.classList.add('csstransforms3d');
    } else {
      document.documentElement.classList.add('no-csstransforms3d');
    }

    问题是,尽管有些浏览器,比如火狐,通过了测试,但是它们有一些已知的错误,比如 Mozilla's backface-visibility bug 所以我 不得不 浏览器嗅探:(.
    我很快发现了火狐的有用结果: if (navigator.userAgent.includes('Firefox')) 但是对于另一个浏览器,我的电脑上有一个叫做“百度浏览器”,我找不到任何结果。
    那么如何检测这些浏览器呢?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Dinesh Pandiyan    6 年前

    您可以使用以下代码在JavaScript中检测流行的浏览器。

    // Mobile Browsers
    export const isMobile = () => {
      const ua = (navigator || {}).userAgent;
      if (ua) {
        return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(ua))
      }
      return false;
    }
    
    // Opera 8.0+
    export const isOpera = () => {
      let opr = window.opr || {};
      return (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    }
    
    // Firefox 1.0+
    export const isFirefox = () => typeof InstallTrigger !== 'undefined';
    
    // Safari 3.0+ "[object HTMLElementConstructor]" 
    export const isSafari = () => {
      let safari = window.safari || {};
      return /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
    }
    
    // Internet Explorer 6-11
    export const isIE = () => /*@cc_on!@*/false || !!document.documentMode;
    
    // Edge 20+
    export const isEdge = () => !isIE() && !!window.StyleMedia;
    
    // Chrome 1+
    export const isChrome = () => !!window.chrome && !!window.chrome.loadTimes;
    

    因此,任何与这些流行浏览器不匹配的东西都将是不受欢迎的浏览器。