指南
如何在 Capacitor 中使用 Persistent UUID
使用 @capgo/capacitor-persistent-uuid
为 Capacitor 生成一个持久化的应用级 UUID,即使在应用重新安装或更新导致常规存储被清除时,也能保持该 ID 稳定。
安装
npm install @capgo/capacitor-persistent-uuid
npx cap sync
插件暴露的内容
- getId - 读取存储的 UUID,若所选 scope 下不存在则创建一个。
- resetId - 轮换存储的 UUID,适用于注销、隐私重置或测试清理流程。
- scope - 可选命名空间,适用于调试版与生产版包名不同的应用。
用法示例
import { PersistentUuid } from '@capgo/capacitor-persistent-uuid';
const { id, created, scope } = await PersistentUuid.getId();
console.log(id);
console.log(created);
console.log(scope);
在不同 Build 变体间共享同一个 UUID
const result = await PersistentUuid.getId({
scope: 'com.example.app',
});
console.log(result.id);
重置标识符
const replacement = await PersistentUuid.resetId();
console.log(replacement.id);
平台注意事项
Android 将 UUID 存储在 AccountManager 中,因此在包名或自定义 scope 保持稳定时,即使经历 Android Studio 重装或 Debug 与 Play 签名差异也能保留。iOS 将 UUID 存储在 Keychain 中,在应用及 iOS 更新期间保持持久,只要 Keychain 访问权限兼容即可。Web 端则使用 localStorage 作为开发环境的备选方案。
本插件不暴露硬件 ID,且在恢复出厂设置、手动删除账号、清除 Keychain、清除浏览器存储或调用 resetId 后将无法保留。
完整参考
- GitHub: https://github.com/Cap-go/capacitor-persistent-uuid/
- 文档: /docs/plugins/persistent-uuid/
继续探索
如果你正在使用 @capgo/capacitor-persistent-uuid 若要保持应用身份稳定,请配合使用 @capgo/capacitor-persistent-uuid 查看概览, 快速入门 查看安装与 API 示例, Android 行为 查看重新安装详情, iOS 行为 查看 Keychain 详情,以及 @capgo/capacitor-persistent-account 当你需要持久化账户数据而非 UUID 时。