思路是通过使用微信的SDK(https://res.wx.qq.com/open/js/jweixin-1.3.2.js)提供的wx.miniProgram.getEnv方法来判断当前环境。
直接用下面的代码,或者用我写好的页面直接放到小程序的web-view里面测试:https://liuxiaofan.com/test/mp.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> 1111 <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script> <script> var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == "micromessenger") { //ios的ua中无miniProgram,但都有MicroMessenger(表示是微信浏览器) wx.miniProgram.getEnv((res) => { if (res.miniprogram) { alert("在小程序里") } else { alert("不在小程序") } }) } else { alert("不在微信") } </script> </body> </html>