Skip to content

platform

运行时平台检测(H5 / 小程序 / App)及 H5 环境下安全的 DOM、Blob URL 访问工具。

环境要求

  • 推荐在 UniApp 运行时 使用;getPlatform() 会尝试调用 getSystemInfoSync(依赖全局 uni
  • H5 相关工具(getWindowsafeQuerySelector 等)仅在浏览器环境有效
  • 本模块使用依赖注入;平台常量 isH5 / isMP / isApp 在模块加载时求值一次

getPlatform

函数签名

typescript
function getPlatform(): string

参数

无。

返回值

类型说明
string平台标识:'h5''mp-weixin''mp-alipay''app-plus''app''quickapp''other'

isH5 / isMP / isApp

函数签名

typescript
const isH5: boolean   // getPlatform() === 'h5'
const isMP: boolean   // getPlatform().startsWith('mp-')
const isApp: boolean  // getPlatform() === 'app-plus' || getPlatform() === 'app'

返回值

类型说明
boolean模块初始化时根据 getPlatform() 结果计算的布尔常量

getWindow / getDocument

函数签名

typescript
function getWindow(): Window | null
function getDocument(): Document | null

返回值

类型说明
Window | null / Document | nullH5 环境返回全局对象;小程序 / App 返回 null

isHTMLElement / isHTMLInputElement

函数签名

typescript
function isHTMLElement(el: any): el is HTMLElement
function isHTMLInputElement(el: any): el is HTMLInputElement

参数

参数名类型必填说明
elany待检测对象

返回值

类型说明
boolean非 H5 平台恒为 false;H5 下使用 instanceof 判断

safeQuerySelector / safeQuerySelectorAll

函数签名

typescript
function safeQuerySelector(selector: string, root?: Element | Document | null): Element | null
function safeQuerySelectorAll(selector: string, root?: Element | Document | null): NodeListOf<Element> | null

参数

参数名类型必填说明
selectorstringCSS 选择器
rootElement | Document | null查询根节点,默认 document

返回值

类型说明
Element | null / NodeListOf<Element> | null查询成功返回节点;无 DOM 或异常时返回 null

safeCreateObjectURL / safeRevokeObjectURL

函数签名

typescript
function safeCreateObjectURL(file: File | Blob): string
function safeRevokeObjectURL(url: string): void

参数

参数名类型必填说明
fileFile | Blob是(create)待创建 URL 的对象
urlstring是(revoke)先前创建的 blob URL

返回值

类型说明
string / void非 H5 或不可用时 create 返回空字符串;revoke 静默忽略

工作原理

  1. getPlatform 检测顺序:先判断是否存在 windowdocument → 再调用 uni.getSystemInfoSync() 读取 platform 字段 → 映射为 h5、各 mp-*app-plus;异常时回退到 H5 检测,最终默认 'other'
  2. isH5 / isMP / isApp 在模块加载时计算,若运行中平台变化不会自动更新(一般场景下平台不变)。
  3. H5 安全 API 在调用 DOM / URL 方法前先检查平台与对象可用性,避免在小程序 / App 环境访问不存在的浏览器 API 导致崩溃。
  4. safeCreateObjectURL 在非 H5 返回 '' 而非抛错,便于跨平台代码统一编写。