需求
项目中要求设备监控获取当前浏览器信息以及版本(PC端项目)
效果图
实现
browser文件
在utils文件夹下创建browser.js文件
const navigator = window.navigator
/* 判断各个浏览器版本号 */
function matchVersion() {
const userAgent = navigator.userAgent
const rMsie = /(msie\s|trident.*rv:)([\w.]+)/
const rEdge = /(edg)\/([\w.]+)/
const rFirefox = /(firefox)\/([\w.]+)/
const rOpera = /(opera).+version\/([\w.]+)/
const rChrome = /(chrome)\/([\w.]+)/
const rSafari = /version\/([\w.]+).*(safari)/
const ua = userAgent.toLowerCase()
var match = rMsie.exec(ua)
if (match !== null) {
return {
browser: 'IE',
version: match[2] || '0'
}
}
var rEmatch = rEdge.exec(ua)
if (rEmatch !== null) {
return {
browser: 'Edge',
version: rEmatch[2] || '0'
}
}
var rFmatch = rFirefox.exec(ua)
if (rFmatch !== null) {
return {
browser: rFmatch[1] || '',
version: rFmatch[2] || '0'
}
}
var rOmatch = rOpera.exec(ua)
if (rOmatch !== null) {
return {
browser: rOmatch[1] || '',
version: rOmatch[2] || '0'
}
}
var rCmatch = rChrome.exec(ua)
if (rCmatch !== null) {
return {
browser: rCmatch[1] || '',
version: rCmatch[2] || '0'
}
}
var rSmatch = rSafari.exec(ua)
if (rSmatch !== null) {
return {
browser: rSmatch[2] || '',
version: rSmatch[1] || '0'
}
}
if (match !== null) {
return {
browser: '',
version: '0'
}
}
}
const browser= {
matchVersion: matchVersion
}
export default browser
index.vue文件
<template>
<div>
<div>浏览器:<span>{{ browser }}</span></div>
<div>浏览器版本:<span>{{ version }}</span></div>
</div>
</template>
<script>
import browser from'@/utils/browser'
export default {
data() {
return {
browser: null,
version: null
}
},
created() {
this.init()
},
methods: {
async init() {
const obj = browser.matchVersion() // { "browser": "chrome", "version": "115.0.0.0" } 浏览器及版本
this.browser= obj.browser
this.version = obj.version
}
}
}
</script>