learning-note icon indicating copy to clipboard operation
learning-note copied to clipboard

对浏览器检测的封装

Open jackPanyj opened this issue 9 years ago • 0 comments

前端浏览器,各种各样。主要有ie, chrome, firefox等。

有些时候不得不对个别的浏览器进行单独检测,然后分别对不同的浏览器写出不同的代码。

所以把浏览器检测封装成了一个模块。

代码如下:


browser.js

// 浏览器判断
const CHROME = 'chrome'
const FIREFOX = 'firefox'
const SAFARI = 'safari'
const OPERA = 'opera'
const IE = 'ie'

var ua = navigator.userAgent.toLowerCase()
var s =
(ua.match(/trident\/([\d.]+)/)) ? IE
: (ua.match(/firefox\/([\d.]+)/)) ? FIREFOX
: (ua.match(/chrome\/([\d.]+)/)) ? CHROME
: (ua.match(/opera.([\d.]+)/)) ? OPERA
: (ua.match(/version\/([\d.]+).*safari/)) ? SAFARI : 0

export default {
  CHROME,
  FIREFOX,
  SAFARI,
  OPERA,
  IE,
  is: s
}

使用方法

import browser from 'browser.js'

if (browser.is === browser.IE) {
  // todo
}

jackPanyj avatar Jul 10 '16 05:07 jackPanyj