platform
运行时平台检测(H5 / 小程序 / App)及 H5 环境下安全的 DOM、Blob URL 访问工具。
环境要求
- 推荐在 UniApp 运行时 使用;
getPlatform()会尝试调用 getSystemInfoSync(依赖全局uni) - H5 相关工具(
getWindow、safeQuerySelector等)仅在浏览器环境有效 - 本模块不使用依赖注入;平台常量
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 | null | H5 环境返回全局对象;小程序 / App 返回 null |
isHTMLElement / isHTMLInputElement
函数签名
typescript
function isHTMLElement(el: any): el is HTMLElement
function isHTMLInputElement(el: any): el is HTMLInputElement参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
el | any | 是 | 待检测对象 |
返回值
| 类型 | 说明 |
|---|---|
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参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
selector | string | 是 | CSS 选择器 |
root | Element | Document | null | 否 | 查询根节点,默认 document |
返回值
| 类型 | 说明 |
|---|---|
Element | null / NodeListOf<Element> | null | 查询成功返回节点;无 DOM 或异常时返回 null |
safeCreateObjectURL / safeRevokeObjectURL
函数签名
typescript
function safeCreateObjectURL(file: File | Blob): string
function safeRevokeObjectURL(url: string): void参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
file | File | Blob | 是(create) | 待创建 URL 的对象 |
url | string | 是(revoke) | 先前创建的 blob URL |
返回值
| 类型 | 说明 |
|---|---|
string / void | 非 H5 或不可用时 create 返回空字符串;revoke 静默忽略 |
工作原理
getPlatform检测顺序:先判断是否存在window与document→ 再调用uni.getSystemInfoSync()读取platform字段 → 映射为h5、各mp-*或app-plus;异常时回退到 H5 检测,最终默认'other'。isH5/isMP/isApp在模块加载时计算,若运行中平台变化不会自动更新(一般场景下平台不变)。- H5 安全 API 在调用 DOM / URL 方法前先检查平台与对象可用性,避免在小程序 / App 环境访问不存在的浏览器 API 导致崩溃。
safeCreateObjectURL在非 H5 返回''而非抛错,便于跨平台代码统一编写。