数据与日志
本页介绍微应用的四类基础数据能力:存储(storage)、设置(settings)、日志(logger)与自身信息(info)。
storage 存储
xunlei.storage 是微应用的私有键值对存储:同一个微应用的页面运行时和事件运行时共享同一份数据,不同微应用之间相互隔离。数据会持久化(宿主重启不丢失),适合保存登录 token、用户偏好、任务缓存等私有数据。页面未打开时,事件脚本仍可读写这份存储。
ts
await xunlei.storage.set('token', 'xxxxxx'); // 写入
const token = await xunlei.storage.get('token'); // 读取,不存在时返回 ''
await xunlei.storage.remove('token'); // 删除单个 key
const keys = await xunlei.storage.keys(); // 所有 key 列表
await xunlei.storage.clear(); // 清空全部| API | 返回 | 说明 |
|---|---|---|
get(key) | Promise<string> | 读取,不存在时返回空字符串 "" |
set(key, value) | Promise<void> | 写入,不存在则创建 |
remove(key) | Promise<void> | 移除指定 key |
clear() | Promise<void> | 清空所有数据 |
keys() | Promise<string[]> | 返回全部 key |
页面与事件脚本共享数据
例如,页面保存用户选择的画质后,事件脚本可以读取同一个 key:
ts
// 页面运行时
await xunlei.storage.set('preferredQuality', 'high');ts
// 事件脚本运行时
xunlei.events.onResolve(async (ctx) => {
const quality = await xunlei.storage.get('preferredQuality'); // 'high'
// 根据 quality 解析 ctx.req.url,并设置 ctx.res
});反过来,事件脚本写入的数据也能由页面读取。读写操作均为异步调用:写入完成后再读取。两个运行时各有自己的 JS 全局变量和生命周期;需要跨运行时保留或传递的数据,应写入 xunlei.storage,不能依赖页面变量或事件脚本的内存状态。
值只能是字符串
所有 value 都是 string 类型。存储对象 / 数组时自行序列化:
ts
await xunlei.storage.set('history', JSON.stringify(list));
const list = JSON.parse(await xunlei.storage.get('history') || '[]');典型用法——「无 token 则登录,有 token 则复用」:
ts
let token = await xunlei.storage.get('token');
if (!token) {
token = await login(); // 自定义登录逻辑
await xunlei.storage.set('token', token);
}settings 设置读取
xunlei.settings 用于读取用户在设置界面中配置的参数。设置界面由迅雷根据 manifest 的 settings 声明自动渲染,微应用内只读:
ts
const quality = xunlei.settings.quality; // "high"
const maxRetries = xunlei.settings.maxRetries; // 3- 属性名与
manifest.settings[].name一一对应; - 读取是同步的(只读快照,在运行环境创建时注入);
- 访问未声明的设置项返回
undefined; - 在代码中给
xunlei.settings.xxx赋值不会改变持久化设置——修改设置只能由用户在设置界面完成。
读取值的优先级:用户保存值 > manifest 声明的 value 默认值 > 类型默认值(string 为 ""、number 为 0、boolean 为 false)。
storage 与 settings 的区别
xunlei.storage | xunlei.settings | |
|---|---|---|
| 声明方式 | 无需声明,按需使用 | 必须在 manifest 中预先声明 |
| 值类型 | string | string / number / boolean |
| 界面 | 无 | 宿主自动渲染设置界面 |
| 谁来写 | 微应用代码 | 用户在设置界面保存 |
| 适用 | 微应用私有数据 | 用户可配置的参数 |
logger 日志
通过 xunlei.logger 输出日志,日志由迅雷统一收集持久化,并自动带上微应用标识前缀:
ts
xunlei.logger.debug('调试信息', ctx);
xunlei.logger.info('任务创建成功:', task.id);
xunlei.logger.warn('配置缺失,使用默认值');
xunlei.logger.error('下载失败:', error.message);| 级别 | 用途 |
|---|---|
debug | 开发调试信息,仅在开发者模式安装的微应用中输出 |
info | 一般运行信息 |
warn | 警告,不影响功能但值得关注 |
error | 错误,影响功能正常运行 |
正式发布请用 info 及以上
debug 级别日志只在开发者模式下生效。需要保留的日志请使用 info / warn / error。
日志参数格式与 console.log 一致,支持多参数与格式化。查看日志的方式见本地调试。
info 微应用信息
xunlei.info 是微应用自身的信息(只读快照,同步访问):
ts
xunlei.info.identity; // 运行时唯一标识
xunlei.info.name; // 对应 manifest.name
xunlei.info.author; // 对应 manifest.author,未声明时为 ''
xunlei.info.title; // 对应 manifest.title
xunlei.info.version; // 对应 manifest.version常用于在日志 / 上报数据中标识来源,或在页面中展示当前版本号。
identity 与数据隔离
存储和设置按 identity 隔离。本地调试(目录加载)与商店安装的 identity 来源不同,两边数据互不相通;上架后 identity 由官方保持稳定。详见运行时架构 · 微应用唯一标识。


