您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax |

JavaScript navigator.userAgent获取浏览器信息案例讲解

51自学网 2022-05-02 21:34:20
  javascript

浏览器对于我们来说,可能是最熟悉的工具了。熟知的浏览器Firefox、Opera、Safari、IE、Chrome以外,据说世界上还有近百种浏览器。通常在开发的时候要做到兼容各种浏览器,因此提炼出判断浏览器类型及系统是很重要的。

先来看看什么是User-Agent?User-Agent是HTTP请求中的用户标识,一般发送一个能够代表客户端类型的字符串,比如浏览器类型 操作系统等信息。User-Agent 的约定格式是:应用名,跟一个斜线,跟版本号,剩下的是自由的格式。

此处我只实例展示几个浏览器

Chrome

iphone的safari

IE

接下来封装了获取浏览类型与系统的函数,之后在需要的地方进行调用即可

// 各主流浏览器function getBrowser() {    var u = navigator.userAgent;     var bws = [{        name: 'sgssapp',        it: /sogousearch/i.test(u)    }, {        name: 'wechat',        it: /MicroMessenger/i.test(u)    }, {        name: 'weibo',        it: !!u.match(/Weibo/i)    }, {        name: 'uc',        it: !!u.match(/UCBrowser/i) || u.indexOf(' UBrowser') > -1    }, {        name: 'sogou',        it: u.indexOf('MetaSr') > -1 || u.indexOf('Sogou') > -1    }, {        name: 'xiaomi',        it: u.indexOf('MiuiBrowser') > -1    }, {        name: 'baidu',        it: u.indexOf('Baidu') > -1 || u.indexOf('BIDUBrowser') > -1    }, {        name: '360',        it: u.indexOf('360EE') > -1 || u.indexOf('360SE') > -1    }, {        name: '2345',        it: u.indexOf('2345Explorer') > -1    }, {        name: 'edge',        it: u.indexOf('Edge') > -1    }, {        name: 'ie11',        it: u.indexOf('Trident') > -1 && u.indexOf('rv:11.0') > -1    }, {        name: 'ie',        it: u.indexOf('compatible') > -1 && u.indexOf('MSIE') > -1    }, {        name: 'firefox',        it: u.indexOf('Firefox') > -1    }, {        name: 'safari',        it: u.indexOf('Safari') > -1 && u.indexOf('Chrome') === -1    }, {        name: 'qqbrowser',        it: u.indexOf('MQQBrowser') > -1 && u.indexOf(' QQ') === -1    }, {        name: 'qq',        it: u.indexOf('QQ') > -1    }, {        name: 'chrome',        it: u.indexOf('Chrome') > -1 || u.indexOf('CriOS') > -1    }, {        name: 'opera',        it: u.indexOf('Opera') > -1 || u.indexOf('OPR') > -1    }];     for (var i = 0; i < bws.length; i++) {        if (bws[i].it) {            return bws[i].name;        }    }     return 'other';} // 系统区分function getOS() {    var u = navigator.userAgent;    if (!!u.match(/compatible/i) || u.match(/Windows/i)) {        return 'windows';    } else if (!!u.match(/Macintosh/i) || u.match(/MacIntel/i)) {        return 'macOS';    } else if (!!u.match(/iphone/i) || u.match(/Ipad/i)) {        return 'ios';    } else if (!!u.match(/android/i)) {        return 'android';    } else {        return 'other';    }}

到此这篇关于JavaScript navigator.userAgent获取浏览器信息案例讲解的文章就介绍到这了,更多相关JavaScript navigator.userAgent获取浏览器信息内容请搜索wanshiok.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持wanshiok.com!


vue实现简单滑块验证
Vue日期时间选择器组件使用方法详解
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1