/** * 环境检测器 * * 检测当前运行环境类型,返回统一的环境标识, * 供上层使用以决定加载哪个 Bridge 提供者。 * * @module bridge/detector */ /** 可识别的运行环境 */ export type Environment = 'browser' | 'wechat-mp' | 'uniapp-webview' /** wechat 全局声明扩展 */ interface WechatWindow extends Window { /** 微信 JS-SDK 桥接对象 */ WeixinJSBridge?: Record /** 微信环境标识 */ __wxjs_environment?: string } /** * 全局 uni 对象(uni-app WebView 中存在) * 声明为 any 以避免对 @dcloudio 类型包的硬依赖 */ declare const uni: Record | undefined /** * 检测当前运行环境 * * 判断优先级: * 1. 微信小程序 WebView —— userAgent 含 MicroMessenger 且标记为 miniprogram * 2. uni-app WebView —— 全局存在 uni 对象(且非小程序场景) * 3. 普通浏览器 —— 其余情况降级 * * @returns 环境标识字符串 */ export function detectEnvironment(): Environment { const win = window as WechatWindow // ── 检测微信环境 ── const ua = navigator.userAgent const isWechat = /MicroMessenger/i.test(ua) if (isWechat) { // 检查是否为小程序 WebView // 方式一:WeixinJSBridge 注入的环境标识 // 方式二:页面 URL 参数 __wxjs_environment(少数场景) if (win.__wxjs_environment === 'miniprogram') { return 'wechat-mp' } // 微信 JS-SDK ready 后可通过 WeixinJSBridge 进一步确认, // 但此处仅做同步检测,保守返回 wechat-mp(若 UA 匹配且环境变量已注入) // 否则仍可能为普通微信内置浏览器,暂归为 wechat-mp return 'wechat-mp' } // ── 检测 uni-app WebView ── // uni 对象在 uni-app 的 WebView 环境中由框架注入 if (typeof uni !== 'undefined' && uni !== null) { return 'uniapp-webview' } // ── 默认:普通浏览器 ── return 'browser' } /** * 判断当前是否在微信小程序 WebView 中 */ export function isWechatMiniProgram(): boolean { return detectEnvironment() === 'wechat-mp' } /** * 判断当前是否在 uni-app WebView 中 */ export function isUniappWebView(): boolean { return detectEnvironment() === 'uniapp-webview' } /** * 判断当前是否为普通浏览器环境 */ export function isBrowser(): boolean { return detectEnvironment() === 'browser' }