浏览器对于我们来说,可能是最熟悉的工具了。熟知的浏览器Firefox、Opera、Safari、IE、Chrome以外,据说世界上还有近百种浏览器。通常在开发的时候要做到兼容各种浏览器,因此提炼出判断浏览器类型及系统是很重要的。
先来看看什么是User-Agent?User-Agent是HTTP请求中的用户标识,一般发送一个能够代表客户端类型的字符串,比如浏览器类型 操作系统等信息。User-Agent 的约定格式是:应用名,跟一个斜线,跟版本号,剩下的是自由的格式。
此处我只实例展示几个浏览器
Chrome
iphone的safari
IE
接下来封装了获取浏览类型与系统的函数,之后在需要的地方进行调用即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | // 各主流浏览器 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获取浏览器信息内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!
- 本文固定链接: https://zxbcw.cn/post/219815/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)