企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
# 浏览器端判断当前设备的运行环境 可判断环境: * android * iOS * weixin * Linux * windows * IE * Mac 直接先上代码: ~~~javascript let device = function(t) {let userAgent = navigator.userAgent.toLowerCase();let n = function(e) {let t = new RegExp(e + "/([^\\s\\_\\-]+)");return e = (userAgent.match(t) || [])[1],e || !1}let r = {os: function() {if(/windows/.test(userAgent)){return "windows";}else{if(/linux/.test(userAgent)){return "linux";}else{if(/iphone|ipod|ipad|ios/.test(userAgent)){return "ios";}else{if(/mac/.test(userAgent)){return "mac";}}}}return void 0;}(),ie: function() {return !!(window.ActiveXObject || "ActiveXObject" in window) && ((userAgent.match(/msie\s(\d+)/) || [])[1] || "11")}(),weixin: n("micromessenger")};r.android = /android/.test(userAgent);r.ios = "ios" === r.os;return r; } ~~~ 返回结果: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210103204117341.png) 有时你的 App 可能会对 userAgent 插入一段特定的标识,譬如: > Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143`myapp`/1.8.6 Safari/537.36 你要验证当前的 WebView 是否在你的 App 环境,即可通过上述的myapp(即为 Native 给 Webview 插入的标识,可以随意定义)来判断。 ~~~javascript var device = device('myapp'); if(device.myapp){alert('在我的App环境'); } ~~~ 这里借鉴于`layui`的`device`判断方法,如果使用了`layui`的框架,可以直接使用`layui.device()`方法来获取,如果没有可以学习下`贤心`大神的写法。 > Tips: layui是贤心大神的作品,大家可以去膜拜一下,https://www.layui.com/ >