Files
yuto-water-h5/src/bridge/detector.ts
Ubuntu ffbdb093a9 feat: project scaffold + bridge + maplibre engine
- Vite + Vue 3 + TypeScript strict
- @yuto-water/js-bridge (types, detector, browser provider)
- MapLibre engine (MapManager singleton, MapFactory, LayerFactory)
- Map composables (useMap, useLayer, usePopup)
- Tianditu tile source, 6 layer type factory
- SCSS design tokens (water-blue theme, dark mode)
- Vant 4, maplibre-gl, axios, pinia, echarts deps
- Build passes (vue-tsc + vite)
2026-06-15 20:46:30 +08:00

88 lines
2.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 环境检测器
*
* 检测当前运行环境类型,返回统一的环境标识,
* 供上层使用以决定加载哪个 Bridge 提供者。
*
* @module bridge/detector
*/
/** 可识别的运行环境 */
export type Environment = 'browser' | 'wechat-mp' | 'uniapp-webview'
/** wechat 全局声明扩展 */
interface WechatWindow extends Window {
/** 微信 JS-SDK 桥接对象 */
WeixinJSBridge?: Record<string, unknown>
/** 微信环境标识 */
__wxjs_environment?: string
}
/**
* 全局 uni 对象uni-app WebView 中存在)
* 声明为 any 以避免对 @dcloudio 类型包的硬依赖
*/
declare const uni: Record<string, unknown> | 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'
}