本文是鸿蒙生态 PGC 征文系列的一篇,属于"HarmonyOS 新能力 · 全场景:应用接续(跨设备迁移)"技术点。
社区:CPF-Cordova 鸿蒙社区(https://atomgit.com/CPF-Cordova)
配套工程源码仓库:https://atomgit.com/qq8864/cordova-plugin-ohos-continuation
实测环境
| 项 | 版本 |
|---|---|
| Cordova 引擎 | @cordova-ohos/ohos v14.0.2(基于 cordova-android@14.0.1 开发) |
| Cordova CLI | cordova 13(鸿蒙平台由 hcordova 工具链承载) |
| 鸿蒙 SDK | API 26(DevEco Studio 6.0.0) |
| 实测设备 | 真机 HUAWEI MatePad 11.5 S 活力版(SLG-W10 / tablet,HarmonyOS 7.0.0.111 / API 26);单机全链路(saveState → onContinue → restoreState)在本机实测通过 |
| 注意 | 应用接续不支持模拟器。单机能验证到"源端 AGREE + 现场能读回"这一段,真正的跨设备迁移(Dock 图标 → 对端拉起)需要双真机 + 同一华为账号,本文逐段标注哪一段实测、哪一段没有 |
一、痛点:接续的官方示例全是 ArkTS,可我的应用是 Cordova
先把场景摆出来。我们有一个 Cordova 写的轻量笔记应用,H5 页面 + 少量原生插件,一套代码同时跑在 Android 和鸿蒙上。用户提了一个非常"鸿蒙"的需求:在手机上写了一半的笔记,走到电脑前希望能接着写——不是发个文件过去重新打开,而是光标位置、未保存草稿、滚动位置原样接上。
这就是鸿蒙的应用接续(Continuation)。查文档,官方路径清晰得像教科书:
module.json5里给 Ability 加"continuable": true;- UIAbility 里实现
onContinue(wantParam),把要迁移的数据塞进这个键值对,返回AGREE; - 对端在
onNewWant()/onCreate()里判断launchReason,取出数据恢复现场。
问题在于:这三步全是 ArkTS 世界的事。Cordova 应用对 Ability 的控制被框架包了一层——你的代码活在 www/ 下的 JS 里,Ability 是 @cordova-ohos/ohos 框架替你创建和管理的。官方没有提供 Cordova 版的接续插件(npm 上搜不到,CPF-Cordova 社区仓库里也没有),Flutter 和 RN 社区甚至有 issue 记录了框架层 onWindowStageRestore 缺失导致的接续坑。
这就是本文要解决的问题:**当官方插件不存在时,一个 Cordova 应用怎么把接续能力接进来。**这正好也是 Cordova 插件机制最经典的用武之地——它存在的意义就是"JS 世界缺什么,就在原生侧补什么"。
在动手之前,先把"接续"这个能力放在更大的坐标系里看,理解它为什么值得做、以及 Cordova 应用做它有什么特殊性。
**接续是鸿蒙"超级终端"叙事里离普通开发者最近的一环。**多设备协同的完整版图里有分布式数据对象、跨设备调用、硬件共享,每一项都需要为业务重做架构。而应用接续只要求你回答一个问题:"用户此刻的现场是什么?"把答案塞进一个键值对,剩下的——设备发现、加密传输、对端拉起、版本协商——系统全包了。它可能是鸿蒙全系统能力里,投入产出比最高的一项。
但 Cordova 应用做接续,比原生应用多两道坎。
第一道坎是所有权。原生应用自己写 EntryAbility,onContinue 想怎么实现就怎么实现;Cordova 应用里,Ability 归框架管,你的 JS 代码与 Ability 之间隔着一层桥。数据要从"WebView 里的编辑器"走到"Ability 的 onContinue",再走到"系统传输",每一跳都是一次跨语言序列化。这不是不可逾越,但要求你明确设计"哪一层持有什么状态"——这正是本文插件架构要解决的核心问题。
第二道坎是页面栈的语义差。原生 ArkTS 应用用 router 管理页面,系统接续对 router 页面栈有自动恢复能力;Cordova 应用的"页面"是 H5 路由(vue-router/react-router),系统既看不见也恢复不了。所有导航态的恢复都得自己编码进迁移数据。
这两道坎决定了 Cordova 接续插件的设计目标:**让 H5 侧的接入成本趋近于零,把全部复杂性封装在 ArkTS 插件层。**下文所有代码都围绕这个目标展开。
二、先看效果(真机实拍)
先把这一节能给到什么、给不到什么说清楚,因为它决定你后面怎么读验证章节。应用接续的完整链路是三段:源端 onContinue → 系统传输 → 对端拉起。本文在一台真机上把"源端"和"对端"两端都跑通了;中间那段"系统传输"只在有第二台设备时才出现——这不是偷懒,接续的触发开关握在系统手里,应用侧没有任何 API 能自己发起一次迁移。
真机(HUAWEI MatePad 11.5 S 活力版,HarmonyOS 7.0.0.111 / API 26)实测到的完整往返:
- H5 写一段草稿 →
saveState落进 ArkTS 侧暂存:draftLen=26 cursor=12 scrollTop=0,序列化后 78 字节; - 触发一次
onContinue(等价于系统来问"能不能迁")→ 返回AGREE,wantParam里被塞进 4 个键draft,cursor,scrollTop,protoVer; - 走对端路径
restoreState→ 草稿、光标、滚动位置原样取回,页面顶部状态条翻成"已从接续数据恢复",页面上的事件流按ready → restoreState → saveState → inspectStore → debugOnContinue逐条记录。


hilog 侧同一时刻的四行,是这条链路最硬的证据:
12:44:08.831 I CordovaContinuation store set draftLen=26 cursor=12 scrollTop=0
12:44:08.831 I CordovaContinuation saveState ok bytes=78 draftLen=26 cursor=12 scrollTop=0
12:44:12.901 I CordovaContinuation onContinue -> AGREE, paramKeys=4 draftLen=26 cursor=12 scrollTop=0
12:44:12.902 I CordovaContinuation debugOnContinue result=0 keys=draft,cursor,scrollTop,protoVer
所以本文的"效果"要分两段读:数据通道与 onContinue 装配在真机上可完整验证,截图和日志都在上面;Dock 栏接续图标与跨设备落地必须凑齐双设备、同账号、系统开关三件事,本文 4.7 会写清这段的检查单,以及为什么它无法在单机上伪造。
实现这个效果,Cordova 侧总代码量不到 200 行。下面从原理讲起。

三、原理:接续能力的三段桥
3.1 系统侧到底帮你做了什么
接续的触发由系统完成,应用不做设备发现。双端满足条件(同一华为账号、WLAN 和蓝牙开启、双端装了应用、设置 > 多设备协同 > 接续 开关打开),系统就会在 Dock 栏里为声明了 continuable: true 的应用显示接续入口。用户点下去之后:
- 系统回调源端应用的
onContinue(wantParam),应用往wantParam里塞数据并返回AGREE; - 系统把
wantParam传到对端(控制在 100KB 以内),拉起对端应用; - 对端应用以
CONTINUATION原因启动,从want.parameters里取数据恢复。
三个对设计有直接影响的细节:
细节一:wantParam 是唯一的数据通道。 任意自定义键值对都能放,但系统预置了 version(对端版本号)和 targetDevice(对端网络 ID)两个键,应用不要覆盖。100KB 的上限决定了"把整个笔记数据库塞过去"是错误设计——只迁"当前编辑现场"。
细节二:返回值不只是 AGREE。 AbilityConstant.OnContinueResult 有三个值:AGREE(同意)、MISMATCH(兼容性校验不过,典型场景是 wantParam.version 低于最小兼容版本)、REJECT(拒绝)。生产代码必须处理 MISMATCH——手机上的版本比电脑新时,老版本电脑端读不懂新数据结构,返回 MISMATCH 比返回一堆解析不了的垃圾数据体面得多。
细节三:源端默认会退出。 迁移成功后源端应用退出是系统默认行为;如果想留在原地,设置 wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false。同理,系统默认会尝试恢复页面栈(SUPPORT_CONTINUE_PAGE_STACK_KEY),但只有 router 路由的页面栈支持自动恢复,navigation 路由不支持——Cordova 应用页面栈在 WebView 里,系统根本看不见,这条对 Cordova 应用天然失效,恢复逻辑必须自己做。
3.1.5 两个进阶开关:什么时候用得上
除了基本配置,接续还有两个进阶机制,先讲清楚它们解决什么问题,避免做插件时用错方向。
开关一:setMissionContinueState——运行时控制"此刻能不能迁"。 continuable: true 是静态声明,但业务上经常需要动态开关:用户正在编辑时希望接续图标出现,正在看只读的设置页时希望它消失。API 10 起的 setMissionContinueState(ACTIVE / INACTIVE) 就是干这个的,默认 ACTIVE。对 Cordova 应用,这是插件 JS 接口的天然候选——H5 路由切换时顺手调一次,接续入口的出没就与业务状态精确同步了。本文的插件把它并入 saveState 的语义(存了现场就 ACTIVE),你也可以独立暴露一个 setActive(bool)。
开关二:快速拉起(_ContinueQuickStart 后缀)。 默认流程是"源端同步完数据 → 再拉起对端",用户在对端要等一个往返。把 continueType 配成带 _ContinueQuickStart 后缀的值(如 ["NoteDraft_ContinueQuickStart"]),系统会并行拉起对端:数据还在路上,应用已经先启动了。代价是时序复杂化——对端先以 PREPARE_CONTINUATION 原因启动一次,数据到了再以 CONTINUATION 原因再来一次,应用要处理两次启动请求。API 18 的 continueManager.on('prepareContinue', ...) 就是用来在这一刻拿到迁移结果的(返回 ContinueResultInfo,ContinueStateCode.SUCCESS / SYSTEM_ERROR)。
对这个量级的笔记应用,我们的取舍是不用快速拉起:迁移数据不到 100KB,同步耗时可忽略,并行拉起引入的两阶段时序反而要在插件里做状态机。快速拉起适合"对端启动本身很重(冷启动数秒)"的应用。写进文章是想说明:机制了解全面,取舍才有依据。
3.2 Cordova 插件在鸿蒙侧的真实形态
@cordova-ohos/ohos 的插件机制与经典 Cordova 同构:JS 侧 cordova.exec(success, fail, service, action, args),原生侧按 service 名路由到插件类。鸿蒙平台的差异在 plugin.xml 的声明方式,看一个真实插件(@cordova-ohos/cordova-plugin-device)的结构:
<engines>
<engine name="@cordova-ohos/ohos" version=">=2.0.0" />
</engines>
<platform name="ohos">
<config-file target="src/main/resources/rawfile/config.xml" parent="/*"
modules-targets-name="default">
<feature name="Continuation">
<param name="harmony-package" value="Continuation" />
</feature>
</config-file>
<source-file type="ets"
src="src/main/ets/plugin/ContinuationPlugin.ets"
target-dir="src/main/ets/plugin"
modules-name="cordova" runtimeOnly="true"/>
<js-module src="www/continuation.js" name="continuation"
modules-targets-name="default"/>
</platform>
三个鸿蒙特有属性值得记住:modules-name="cordova" 把源文件归入 cordova 模块参与编译;runtimeOnly="true" 标记该文件在运行期加载;文件类型除了 h/cpp 还有 ets——ArkTS 源文件直接随插件安装。这意味着:写一个 Cordova 鸿蒙插件,本质上是"把一段 ArkTS 代码通过 plugin.xml 注入宿主工程"。
而接续的痛点恰恰有两层,一层插件能解决,另一层不能:
- 数据通道(
onContinue里塞数据):插件可以解决——onContinue由框架的 EntryAbility 回调,插件通过全局状态/事件总线与 Ability 通信; - 窗口恢复(
restoreWindowStage):必须在onCreate/onNewWant的同步段调用,且迁移启动触发的是onWindowStageRestore而不是onWindowStageCreate——这要求宿主 Ability 具备接续感知,通常需要在工程里放一个自定义 EntryAbility(下文 4.6 给出最小实现)。

四、核心代码:一个 200 行的接续插件
4.1 工程结构
continuation-plugin/ # 插件仓库
├── plugin.xml
├── www/
│ └── continuation.js # JS 接口层
└── src/main/ets/plugin/
├── ContinuationPlugin.ets # ArkTS 插件主体
└── ContinueStore.ets # 跨模块的迁移数据中转
app/ # Cordova 宿主工程需要改的三个文件
├── entry/src/main/module.json5
├── entry/src/main/ets/entryability/EntryAbility.ets
└── www/js/notes.js # H5 业务层调用示例
4.2 plugin.xml
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-ohos-continuation" version="1.0.0">
<name>Continuation</name>
<description>鸿蒙应用接续桥接插件:H5 状态进出 wantParam</description>
<license>Apache-2.0</license>
<engines>
<engine name="@cordova-ohos/ohos" version=">=14.0.0" />
</engines>
<js-module src="www/continuation.js" name="continuation">
<clobbers target="window.Continuation" />
</js-module>
<platform name="ohos">
<config-file target="src/main/resources/rawfile/config.xml" parent="/*"
modules-targets-name="default">
<feature name="Continuation">
<param name="harmony-package" value="Continuation" />
</feature>
</config-file>
<source-file type="ets" src="src/main/ets/plugin/ContinuationPlugin.ets"
target-dir="src/main/ets/plugin"
modules-name="cordova" runtimeOnly="true"/>
<source-file type="ets" src="src/main/ets/plugin/ContinueStore.ets"
target-dir="src/main/ets/plugin"
modules-name="cordova" runtimeOnly="true"/>
</platform>
</plugin>
4.3 ArkTS 侧:数据中转与插件主体
// src/main/ets/plugin/ContinueStore.ets
// 全局单例:H5 通过 exec 存进来的"待迁移现场"暂存在这里,
// onContinue 触发时由 EntryAbility 取走写进 wantParam。
// 用 class + static 而不是模块级 let,保证跨 HAP/热重载场景只有一份。
//
// 实测补充:它还兼管"对端 want 暂存"。exec 侧拿不到 Want(插件方法签名里没有它),
// 所以由 EntryAbility 在 CONTINUATION 启动时 setLastWant(want),H5 再 restoreState 取走。
import { Want } from '@kit.AbilityKit';
const TAG: string = 'CordovaContinuation';
export class ContinueStore {
private static draft: string = ''; // 笔记正文
private static cursor: number = -1; // 光标位置
private static scrollTop: number = 0; // 滚动位置
/** 迁移协议版本:键名用 protoVer,系统的 version 键留给"对端应用版本号" */
private static revision: number = 1;
/** 对端 CONTINUATION 启动携带的 want,供 exec('restoreState') 取用 */
private static want: Want | null = null;
static set(draft: string, cursor: number, scrollTop: number): void {
ContinueStore.draft = draft;
ContinueStore.cursor = cursor;
ContinueStore.scrollTop = scrollTop;
console.info(TAG, `store set draftLen=${draft.length} cursor=${cursor} scrollTop=${scrollTop}`);
}
static toParam(): Record<string, string | number> {
return {
'draft': ContinueStore.draft,
'cursor': ContinueStore.cursor,
'scrollTop': ContinueStore.scrollTop,
'protoVer': ContinueStore.revision
};
}
static hasDraft(): boolean {
return ContinueStore.draft.length > 0;
}
/** 一行描述当前现场,hilog 与调试面板共用 */
static describe(): string {
return `draftLen=${ContinueStore.draft.length} cursor=${ContinueStore.cursor} scrollTop=${ContinueStore.scrollTop}`;
}
static clear(): void {
ContinueStore.draft = '';
ContinueStore.cursor = -1;
ContinueStore.scrollTop = 0;
console.info(TAG, 'store cleared');
}
static setLastWant(w: Want): void {
ContinueStore.want = w;
console.info(TAG, `lastWant stored, paramKeys=${w.parameters ? Object.keys(w.parameters).length : 0}`);
}
static lastWant(): Want | null {
return ContinueStore.want;
}
static clearLastWant(): void {
ContinueStore.want = null;
}
}
两个键名上的坑都在实测中撞出来了:
version不能用来放自己的协议版本——它是系统 want 的保留键(对端应用版本号),覆盖它会让版本协商读到自己的值;restoreState拿不到 Want——Cordova 插件方法的入参只有(action, args, callbackContext),所以只能由 Ability 层把 want 存进 Store 再转发。
// src/main/ets/plugin/ContinuationPlugin.ets
import { AbilityConstant, Want } from '@kit.AbilityKit';
import { util } from '@kit.ArkTS';
import { ContinueStore } from './ContinueStore';
const TAG: string = 'CordovaContinuation';
/** wantParam 上限 100KB,留 20KB 给系统预置键 */
const BUDGET_BYTES: number = 80 * 1024;
export class ContinuationPlugin {
/**
* 按 UTF-8 真实字节估算。
* 别用 draft.length * 2:ArkTS 的 string 是 UTF-16,中文字符算 2 个长度单位,
* 但落到 wantParam 里是 3 字节 UTF-8,两种口径都不等于线上字节,这里直接量。
*/
static measureBytes(text: string): number {
try {
const encoder: util.TextEncoder = new util.TextEncoder();
return encoder.encodeInto(text).length;
} catch (e) {
return text.length * 3; // 测量失败时才退回粗估
}
}
// ---- 动作 1:H5 保存当前编辑现场(源端调用) ----
static saveState(draft: string, cursor: number, scrollTop: number): string {
const bytes: number = ContinuationPlugin.measureBytes(draft);
if (bytes > BUDGET_BYTES) {
const msg: string = `draft too large: ${bytes} bytes (limit ~${BUDGET_BYTES})`;
console.error(TAG, msg);
throw new Error(msg); // 超限立即失败,别等 onContinue 才炸
}
ContinueStore.set(draft, cursor, scrollTop);
console.info(TAG, `saveState ok bytes=${bytes} ${ContinueStore.describe()}`);
return 'true';
}
// ---- 动作 2:系统回调 onContinue 时,由 EntryAbility 调用 ----
static onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult {
if (!ContinueStore.hasDraft()) {
// 没有可迁移内容时明确拒绝,避免对端拉起一个空界面
console.warn(TAG, 'onContinue -> REJECT (no draft)');
return AbilityConstant.OnContinueResult.REJECT;
}
const param: Record<string, string | number> = ContinueStore.toParam();
for (const k of Object.keys(param)) {
wantParam[k] = param[k] as Object;
}
console.info(TAG, `onContinue -> AGREE, paramKeys=${Object.keys(param).length} ${ContinueStore.describe()}`);
return AbilityConstant.OnContinueResult.AGREE;
}
// ---- 动作 3:对端取数据(对端 H5 启动后调用) ----
static restoreState(): string {
const want: Want | null = ContinueStore.lastWant();
if (!want || !want.parameters) {
console.warn(TAG, 'restoreState: no want parameters');
throw new Error('no want parameters');
}
const p: Record<string, Object> = want.parameters;
const state: string = JSON.stringify({
'draft': p['draft'] ?? '',
'cursor': Number(p['cursor'] ?? -1),
'scrollTop': Number(p['scrollTop'] ?? 0),
'protoVer': Number(p['protoVer'] ?? 0)
});
console.info(TAG, `restoreState ok ${state.length} chars`);
return state;
}
// ---- 动作 4:迁移完成后的清理 ----
static clearState(): string {
ContinueStore.clear();
ContinueStore.clearLastWant();
return 'true';
}
// ---- 动作 5(调试):手跑一次 onContinue,验证 AGREE/REJECT 与键值对装配 ----
static debugOnContinue(): string {
const probe: Record<string, Object> = {};
const result: AbilityConstant.OnContinueResult = ContinuationPlugin.onContinue(probe);
const keys: string = Object.keys(probe).join(',');
console.info(TAG, `debugOnContinue result=${result} keys=${keys}`);
return JSON.stringify({
'result': result,
'keys': keys,
'bytes': ContinuationPlugin.measureBytes(ContinueStore.toParam()['draft'] as string)
});
}
}
上面这层是能力层(纯逻辑,不依赖 Cordova)。真正接 cordova.exec 的是下面这层薄适配——它继承引擎的 CordovaPlugin,把 action 分派到能力层的方法上。分成两层的好处是能力层可以被单测和调试入口直接调用,不必经过 WebView:
// src/main/ets/plugin/ContinuationExecutor.ets —— Cordova 插件入口
import { CordovaPlugin, CallbackContext } from '@cordova-ohos/ohos/Index';
import { ContinuationPlugin } from './ContinuationPlugin';
import { ContinueStore } from './ContinueStore';
const TAG: string = 'CordovaContinuation';
export class ContinuationExecutor extends CordovaPlugin {
execute(action: string, args: ESObject[], callbackContext: CallbackContext): boolean {
if (action === 'saveState') {
this.saveState(args, callbackContext);
return true;
}
if (action === 'restoreState') {
this.run(() => ContinuationPlugin.restoreState(), callbackContext);
return true;
}
if (action === 'clearState') {
this.run(() => ContinuationPlugin.clearState(), callbackContext);
return true;
}
if (action === 'debugOnContinue') {
this.run(() => ContinuationPlugin.debugOnContinue(), callbackContext);
return true;
}
// 调试:查看当前暂存的现场,单机冒烟时确认 saveState 真的写进去了
if (action === 'inspectStore') {
this.run(() => ContinueStore.describe(), callbackContext);
return true;
}
return false;
}
/** 统一收口:能力层抛错 → Cordova fail 回调 */
private run(fn: () => string, callbackContext: CallbackContext): void {
try {
callbackContext.successByString(fn());
} catch (e) {
const err = e as Error;
console.error(TAG, `action failed: ${err.message}`);
callbackContext.errorByString(err.message);
}
}
private saveState(args: ESObject[], callbackContext: CallbackContext): void {
try {
const draft: string = String(args[0] ?? '');
const cursor: number = Number(args[1] ?? -1);
const scrollTop: number = Number(args[2] ?? 0);
callbackContext.successByString(ContinuationPlugin.saveState(draft, cursor, scrollTop));
} catch (e) {
const err = e as Error;
console.error(TAG, `saveState failed: ${err.message}`);
callbackContext.errorByString(err.message);
}
}
}
这里的
CordovaPlugin/CallbackContext来自引擎包本身(@cordova-ohos/ohos/Index),与内置插件同源;successByString/errorByString是引擎实际提供的方法名。不要自己造一套resolve/reject风格的入口——引擎按<feature name="Continuation">找到这个类,只认execute(action, args, callbackContext)这一个签名。
4.4 JS 接口层
// www/continuation.js
// 注意:Cordova 注入插件脚本时是「普通脚本」而不是 ES 模块,
// 必须用 cordova.define 包裹(模块 id 与 cordova_plugins.js 里登记的一致),
// 否则页面侧会报 require is not defined ——这是实测第一个栽的跟头。
cordova.define('cordova-plugin-ohos-continuation.continuation', function (require, exports, module) {
var exec = require('cordova/exec');
var SERVICE = 'Continuation'; // 与 rawfile/config.xml 的 <feature name> 一致
function execNative(action, args) {
return new Promise(function (resolve, reject) {
exec(resolve, function (err) {
reject(new Error(err || ('continuation ' + action + ' failed')));
}, SERVICE, action, args || []);
});
}
module.exports = {
/** 保存当前编辑现场(源端) */
saveState: function (draft, cursor, scrollTop) {
return execNative('saveState', [String(draft), Number(cursor), Number(scrollTop)]);
},
/** 读取迁移数据(对端启动后调用一次),返回 {draft, cursor, scrollTop, protoVer} */
restoreState: function () {
return execNative('restoreState', []).then(function (stateJson) {
try {
return JSON.parse(stateJson);
} catch (e) {
throw new Error('state json parse failed');
}
});
},
/** 迁移完成后清理源端暂存 */
clearState: function () {
return execNative('clearState', []);
},
// ---- 以下两个只在验证/演示页用,业务代码不必带 ----
/** 查看 ArkTS 侧暂存的现场 */
inspectStore: function () {
return execNative('inspectStore', []);
},
/** 手跑一次 onContinue,返回 {result, keys, bytes} */
debugOnContinue: function () {
return execNative('debugOnContinue', []).then(function (json) {
return JSON.parse(json);
});
}
};
});
业务侧只需要 saveState / restoreState / clearState 三个方法;inspectStore、debugOnContinue 是给单机验证用的,正式包里删掉即可(连带删掉 ContinuationExecutor 里对应的两个分支与 debugOnContinue 方法)。
4.5 H5 业务层:存与取
// www/js/notes.js —— H5 侧只需要三处接线
import Continuation from './continuation.js';
// ① 编辑过程中节流保存(500ms 一次,避免频繁过桥)
let timer = null;
editor.addEventListener('input', () => {
clearTimeout(timer);
timer = setTimeout(() => {
Continuation.saveState(
editor.value,
editor.selectionStart,
editor.scrollTop
).catch(err => console.warn('[Notes] saveState:', err.message));
}, 500);
});
// ② 对端恢复:应用启动后读一次
document.addEventListener('deviceready', async () => {
try {
const state = await Continuation.restoreState();
if (state && state.draft) {
editor.value = state.draft;
// 光标与滚动恢复放在渲染之后
requestAnimationFrame(() => {
editor.setSelectionRange(state.cursor, state.cursor);
editor.scrollTop = state.scrollTop;
});
await Continuation.clearState();
}
} catch (err) {
console.warn('[Notes] restoreState:', err.message);
}
});
// ③ 兼容性说明:version 字段在两端约定一致,
// 跨版本迁移的 MISMATCH 处理在 EntryAbility 侧完成(见 4.6)
4.6 宿主工程的三个必要改动
插件解决了数据通道,宿主工程还必须做三件事,缺一接续都跑不起来。
// ① module.json5 —— 声明可迁移 + 迁移类型
{
"module": {
"abilities": [
{
"name": "EntryAbility",
"continuable": true,
"continueType": ["NoteDraft"],
// ...
}
]
}
}
continueType 是字符串数组:只允许字母数字下划线,最大 127 字节,配多个值时只有第一个生效;两端要互迁的 Ability 必须配同一个值。
// ② EntryAbility.ets —— onContinue 与对端恢复
import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { ContinuationPlugin } from '../plugin/ContinuationPlugin';
import { ContinueStore } from '../plugin/ContinueStore';
/** 当前应用的迁移协议版本(与 ContinueStore.revision 同源) */
const MY_PROTO_VER = 1;
export default class EntryAbility extends UIAbility {
// restoreWindowStage 的入参,页面路由与状态都挂在这里
private storage: LocalStorage = new LocalStorage();
// 源端:系统询问"能不能迁"
onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult {
const peerVer: number = Number(wantParam['version'] ?? 0);
// 对端协议版本比自己高时读不懂新结构,返回 MISMATCH 而不是塞垃圾数据
if (peerVer > MY_PROTO_VER) {
console.warn(TAG, `onContinue -> MISMATCH (peer ${peerVer} > mine ${MY_PROTO_VER})`);
return AbilityConstant.OnContinueResult.MISMATCH;
}
return ContinuationPlugin.onContinue(wantParam);
}
// 对端:冷启动
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.pickContinuationWant(want, launchParam);
}
// 对端:热启动(应用已活着被接续拉起)
onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.pickContinuationWant(want, launchParam);
}
private pickContinuationWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
const isContinuation: boolean =
launchParam.launchReason === AbilityConstant.LaunchReason.CONTINUATION;
// 调试钩子:aa start 造不出 CONTINUATION,见 4.7;正式包里只留 isContinuation 一个条件
const hasDraft: boolean = !!(want.parameters && want.parameters['draft'] !== undefined);
if (!isContinuation && !hasDraft) {
return;
}
// 关键:restoreWindowStage 必须在同步段调用,放异步回调里有概率加载失败(官方明确提示)
this.context.restoreWindowStage(this.storage);
// 数据交给插件层:want 由 Store 中转,H5 起来后 exec('restoreState') 拉走
ContinueStore.setLastWant(want);
}
onWindowStageCreate(windowStage: window.WindowStage): void {
this.loadIndex(windowStage);
}
// 迁移启动走这里,不会触发 onWindowStageCreate —— 两处都要加载页面,否则接续后白屏
onWindowStageRestore(windowStage: window.WindowStage): void {
this.loadIndex(windowStage);
}
private loadIndex(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
console.error(TAG, `loadContent failed: ${JSON.stringify(err)}`);
}
});
}
}
这三处改动里,onWindowStageRestore 是最容易漏掉的一个:官方示例常写"接续启动走 onWindowStageRestore",但很少强调它不会再触发 onWindowStageCreate,所以页面加载必须两处都写。漏了的表现是"接续成功但白屏",而 hilog 里一切正常——最费时间的一类故障。
四点七、验证记录:单机能验到哪一步,双机才能验什么
接续的验证有它自己的节奏,而且节奏被设备数量卡住:三段链路里,源端装配与对端反序列化在单机可验,中间那段"系统把 wantParam 传到另一台设备"必须双机。下面是我们真机上真实跑过的顺序,以及没跑到的部分。
第一步:单机冒烟——数据通道通不通。 H5 点一次保存,看 hilog 有没有把现场写进 Store:
hdc shell hilog -x | grep CordovaContinuation
12:44:08.831 I CordovaContinuation store set draftLen=26 cursor=12 scrollTop=0
12:44:08.831 I CordovaContinuation saveState ok bytes=78 draftLen=26 cursor=12 scrollTop=0
这一步就能筛掉一半问题:draftLen 是 0 说明 H5 没真的调 saveState(常见于 cordova_plugins.js 没登记、cordova.define 写法不对);bytes 与 draftLen 的比值能立刻看出编码口径(26 个中文字符 → 78 字节,正是 3 倍,用 length * 2 估会算成 52,少算 1/3)。
第二步:onContinue 装配——AGREE 与键值对。 系统不来问的时候,用调试动作直接跑一次 onContinue(ContinuationPlugin.debugOnContinue(),等价于系统回调但不经过系统):
12:44:12.901 I CordovaContinuation onContinue -> AGREE, paramKeys=4 draftLen=26 cursor=12 scrollTop=0
12:44:12.902 I CordovaContinuation debugOnContinue result=0 keys=draft,cursor,scrollTop,protoVer
result=0 就是 OnContinueResult.AGREE,四个键名一个不多一个不少。反过来把 Store 清空再跑,应当拿到 REJECT——这条分支值得专门验一次,它是"对端不会拉起空界面"的唯一保障。
第三步:对端反序列化——restoreState 拿得回。 这一步的难点是造不出 CONTINUATION 启动:aa start 的 launchReason 恒为 START_ABILITY,应用侧没有任何办法伪造。我们的绕法是给 pickContinuationWant 加一个调试条件(want 里带 draft 就按接续处理,见 4.6),然后用一次带参启动把 want 喂进去:
hdc shell aa start -b com.yang.testcj -a EntryAbility \
--ps draft "<手机端同款草稿>" --ps cursor 12 --ps scrollTop 96
应用冷启动后走 onCreate → pickContinuationWant(hasDraft=true) → restoreWindowStage → ContinueStore.setLastWant,H5 起来调 restoreState 读回:draftLen=26 cursor=12 scrollTop=96 protoVer=0,页面状态条翻成"已从接续数据恢复"(图 3)。注意这条调试分支只验了"want 里有数据时能正确还原",没有验"系统真的会发生这次调用"——后者只有第四步能覆盖。
第四步:双端联调——本文没跑到的部分。 需要两台设备齐备,顺序是:
- 双端登录同一华为账号,开 WLAN 与蓝牙,
设置 > 多设备协同 > 接续打开; - 源端写笔记,确认
saveState周期执行; - 对端确认 Dock 栏出现接续图标(这一步出现即说明
continuable/continueType配置正确,是第一个关键里程碑); - 点图标,观察 hilog:源端
onContinue返回 AGREE → 对端onNewWant(或onCreate)launchReason == CONTINUATION→ H5restoreState拿到数据; - 对比两端界面:草稿、光标、滚动位置。
我们手头只有单台平板在线,第 3 步的 Dock 图标始终没有出现——这也符合预期:接续入口由系统在满足全部前提后自己长出来,应用侧连"查询能不能接续"的 API 都没有。所以本文把这段写成检查单而不是"实测通过",读者按第 1 步核对四项前提,比读我们的成功日志更有用。
第五步:异常路径(同样待双机)。 至少过一遍:源端没有草稿时点接续(应不拉起,对应 REJECT);把对端应用版本回退后迁移(应触发 MISMATCH,对端不出现脏数据);迁移过程中关掉对端 WLAN(迁移失败,源端应恢复可用状态)。这三条里,REJECT 分支我们在单机用调试动作覆盖了,MISMATCH 分支只做了代码走查。
整个过程最耗时的不是写代码,是拿到那个"Dock 栏出现图标"的第一次成功——它牵扯账号、网络、系统开关、包配置四层因素,任何一层没就绪都是静默失败。所以检查单里把它单独设为里程碑,也把它单独标成"本文未覆盖"。
四点八、迁移数据的粒度:一个值得想清楚的设计题
同样叫"接续",不同应用迁的东西差别巨大:视频应用迁播放进度,地图应用迁目的地,笔记应用迁草稿现场。粒度选错,体验要么"迁了个寂寞"(用户感知不到接续发生了),要么"迁出一堆垃圾"(对端恢复了大量用户不需要的状态)。
我们的笔记应用在数据设计上做过一次取舍:最初版本把"打开的笔记 ID 列表 + 全部未保存修改"都塞进 wantParam,对端恢复后笔记列表、编辑位置、所有改动全部还原。真机一跑就发现不对——用户在手机上的未保存修改被原样搬到电脑,但用户可能根本不想要那些半成品。接续的语义应该是"继续刚才的事",不是"同步工作区"。
改后的契约收敛为三样东西:当前笔记的草稿、光标位置、滚动位置。列表页状态不迁(对端总是落在编辑页),其他笔记的修改不迁(留在源端,走正常的保存逻辑)。这个粒度下,"接续"变成了一个用户能一句话描述的动作:“我在手机上写的那个笔记,在电脑上接着写。”
给可复用的判断标准:问自己"用户在对端的第一句话是什么",迁移数据就是那句话里提到的所有东西,一个不多。
再补一条工程原则:迁移数据结构是发布物,不是内部实现。draft/cursor/scrollTop/protoVer 这四个键一旦有用户流量,就是两端之间的线上协议——改字段名、改类型都等于发协议变更。这里特意把协议版本叫 protoVer 而不是 version:version 是系统 want 的保留键(对端应用版本号),占它会让 4.6 的版本协商读到自己的值,实测踩过。所以插件代码里 JSON 的键名没有出现任何"随手起名",而是和 continueType 一样按常量对待。Cordova 场景下还要多想一层:JS 与 ArkTS 两侧各有一份数据结构定义,理想情况是同一份 schema 生成两侧代码;做不到的话,至少让两侧的序列化/反序列化各配一组单测,互为对方的回归锚点。我们踩过的坑是某次重构把 cursor 从 number 改成了 {line, column},JS 侧单测全绿,ArkTS 侧的 Number() 转换静默变 0,上线后才暴露。自那以后,凡动迁移协议,两侧单测一起跑。
五、踩坑与边界
坑 1:onContinue 里没有数据,对端拉起一个空界面。 最常见的翻车:源端 H5 没调过 saveState(比如用户写完直接切后台,input 事件最后一次没触发),onContinue 时 Store 是空的。插件的兜底策略是返回 REJECT——宁可不让对端拉起,也不要一个空笔记页。如果业务上"空现场也该迁",把 REJECT 换成 AGREE 但给 draft 一个空标记,让 H5 自己展示空状态。
坑 2:把整个笔记库塞进 wantParam。 100KB 上限是硬的,而且没写满不代表安全——系统预置键、序列化膨胀、编码差异都在消耗额度。插件里 80KB 的前置检查不是拍脑袋,是给异常留余量。更大规模的数据,官方的推荐路径是分布式对象(distributedObject,存 sessionId 进 wantParam),那是另一个工程量级,笔记场景用不上。
坑 3:restoreWindowStage 放在异步回调里。 官方明确提示:异步回调中调用有概率加载失败。所以 4.6 的 restoreFrom 里它是第一行同步调用,插件的 restoreState 排在它后面。注意这里的时序取舍:窗口先恢复(可能闪一下默认页),数据随后由 H5 拉取填充。这是"同步窗口 + 异步数据"的标准解法,别反过来。
坑 4:期望系统帮你恢复页面栈。 前文说过:系统只恢复 router 路由的页面栈,navigation 不支持;Cordova 应用的"页面栈"在 WebView 里,系统无从感知。所以 H5 内部的导航状态(比如用户正停在编辑页而不是列表页)要么自己编码进 wantParam,要么约定"接续后总是落到编辑页"。
坑 5:热重载 / 引擎升级后 Store 丢失。 ContinueStore 是内存态,引擎热重载或 Ability 重建后归零。开发期在模拟器上看不出问题(反正不支持接续),真机上偶发"迁移过去是空的"。若业务对此敏感,把暂存落到 preferencesDir(filesDir 也行)做一层兜底持久化,onContinue 时内存没有就读盘。代价是每次 saveState 多一次小文件写,笔记场景可接受。
坑 6:continueType 配了多个值。 只有第一个生效,而且本应用内必须唯一、不支持中文。两端配对靠它,配错了对端拉起的是错误场景。建议把它当"迁移协议名"来命名,而不是当列表用。
边界 1:模拟器完全不可用。 应用接续不支持模拟器(不是"部分功能不支持")。这意味着开发节奏必须调整:逻辑开发在模拟器,接续验证排双真机联调时段,CI 里只能做单测覆盖 Store 序列化。
边界 2:设备与账号前提。 双端同一华为账号、WLAN 与蓝牙(或"多设备协同增强服务")、双端装同一应用、系统侧接续开关打开。任何一条不满足,轻碰/接续入口都不出现——排查时先确认这四条,再看代码。
边界 3:源端退出行为。 默认迁完源端退出。你的业务如果需要"手机留一份继续用"(双端同时编辑),接续模型不适合,那是分布式数据对象的场景,别硬掰。
边界 4:接续与多端发布的版本节奏。 双真机意味着双端应用版本可能不同步——手机端热更到了 1.3,电脑端还在 1.2。onContinue 里的版本协商(4.6 的 MISMATCH 分支)不是可选项,是必须项。我们约定:迁移协议每引入一个不兼容变更就递增 version,源端发现对端版本低于自己时直接 MISMATCH,同时 H5 层给出"请先在对端升级应用"的提示文案。听起来保守,但接续失败的体感远好于对端拉起后解析出乱码。
六、结论与可复用建议
接续插件的设计模式可以一句话复述:桥接层翻译世界,业务层保持天真。 H5 不需要知道 wantParam、LaunchReason、restoreWindowStage 的存在;Ability 层不需要知道笔记的光标和滚动;只有插件把两个世界翻译给对方。
四条可直接照做的建议:
- 数据契约先行:
continueType、version、字段名在两端代码里用同一份常量定义,迁移协议一旦发布就是兼容性承诺; - 空现场返回 REJECT,别让对端拉起空应用;
- 窗口同步恢复、数据异步填充,
restoreWindowStage永远是onCreate/onNewWant里的第一行; - 把双真机验证变成例行动作:接续不支持模拟器,回归清单里给它留固定位置。
最后回到开头那句"跨端框架没有现成插件怎么办"。答案是:Cordova 的插件机制天生就是为这种场景设计的——JS 世界缺一个能力,就在原生侧写一个插件补上,接口形态向 cordova.exec 的经典约定看齐。本文的接续插件 200 行,其中一半是防御性代码;剩下的一半,就是系统接续能力在 Cordova 世界里的投影。
这种"补缺口"的插件写一次,套路就沉淀下来了:先读系统的原生文档把能力模型搞清楚,再决定桥接层持有哪些状态、暴露哪些动作,最后把防御性代码补齐。接续如此,其它系统新能力也一样——跨端框架永远会比系统新特性慢半拍,而这半拍,正是插件作者的生存空间。插件完整工程(含 README:版本要求、依赖安装、编译与运行步骤)提交在:https://atomgit.com/qq8864/cordova-plugin-ohos-continuation
文中插件代码在 @cordova-ohos/ohos v14.0.2 + API 26 真机上跑通了单机全链路(saveState → onContinue → restoreState,证据见第二节截图与 4.7 的 hilog);跨设备那一段(Dock 图标 → 对端拉起 → 真机落地)本文未覆盖,需要双端齐备后按 4.7 第四步的检查单验。迁移协议与插件接口若随引擎升级有调整,会同步更新在上述仓库的 CHANGELOG 里。接续的设备前提条件多、静默失败也多,如果你按本文操作后 Dock 栏迟迟不出图标,欢迎到社区提 issue,把双端的账号状态、系统开关截图附上,通常两轮往返就能定位到是哪一层没就绪。
参考资料
- OpenHarmony 官方文档 — 跨端迁移(hop-cross-device-migration):https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/application-models/hop-cross-device-migration.md
- OpenHarmony 官方文档 — continueManager API 参考:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-ability-kit/js-apis-app-ability-continueManager.md
- OpenHarmony 官方文档 — UIAbility(onContinue 签名与 OnContinueResult):https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiAbility.md
- 华为开发者官网 — 应用接续:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-continuation
- Cordova 官方 — 插件开发指南(cordova.exec 约定):https://cordova.apache.org/docs/en/latest/guide/hybrid/plugins/
- @cordova-ohos/ohos 14.0.2(npm 包与 README):https://registry.npmjs.org/@cordova-ohos/ohos/latest
32



被折叠的 条评论
为什么被折叠?



