JavaScript navigator.userAgent獲取瀏覽器信息案例講解
瀏覽器對于我們來說,可能是最熟悉的工具了。熟知的瀏覽器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獲取瀏覽器信息內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
1. php網絡安全中命令執行漏洞的產生及本質探究2. 三個不常見的 HTML5 實用新特性簡介3. Angular獲取ngIf渲染的Dom元素示例4. php面向對象程序設計介紹5. ASP調用WebService轉化成JSON數據,附json.min.asp6. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁7. 使用.net core 自帶DI框架實現延遲加載功能8. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析9. php測試程序運行速度和頁面執行速度的代碼10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析
