HMRouter is a solution for page redirection on HarmonyOS applications. You can install, configure, and quickly get started with HMRouter by referring to HMRouter Usage Guide. This topic describes how to use the HMRouter framework in various development scenarios. The following features are provided:
The bottom layer of the framework encapsulates related Navigation capabilities to help you reduce the attention to Navigation details and improve development efficiency. In addition, the framework enhances the page redirection capability, such as route interception and singleton pages. The following describes how to use the HMRouter framework in the scenarios such as page redirection, dialog box, transition animation, data loading, and maintenance and debugging.
HMRouter provides the page redirection and return function based on custom annotations. The procedure is as follows:
@HMRouter({ pageUrl: 'ProductContent' })
@Component
export struct ProductContent {
// ...
@State param: ParamsType | null = null;
aboutToAppear(): void {
this.param = HMRouterMgr.getCurrentParam() as ParamsType;
}
// ...
} HMRouterMgr.to('ProductContent')
.withNavigation('mainNavigationId')
.withParam({ a: 1, b: 2 })
.onResult((popInfo: HMPopInfo) => {
const pageName = popInfo.srcPageInfo.name;
const params = popInfo.result;
console.log(`page name is ${pageName}, params is ${JSON.stringify(params)}`);
})
.pushAsync() @Component
export struct ProductContent {
// ...
@State param: ParamsType | null = null;
aboutToAppear(): void {
this.param = HMRouterMgr.getCurrentParam() as ParamsType;
}
// ...
} HMRouterMgr.pop({ navigationId: 'mainNavigationId', param: this.param }) If the page redirection path is HomePage > PageA > PageB > PageC and you want to directly return to HomePage from PageC with parameters, simply use the to() method provided by HMRouterMgr with the target page address and relevant parameters. This enables a direct return to the specified page along with the passed data.
HMRouterMgr.to('MainPage')
.withNavigation('mainNavigationId')
.withParam(0)
.pushAsync() 
When a user does not log in to an application, the login page is automatically redirected to when the user taps some application content. To implement this scenario by using the HMRouter, perform the following steps:
@HMInterceptor({ interceptorName: 'LoginCheckInterceptor' })
export class LoginCheckInterceptor implements IHMInterceptor {
async intercept(chain: IHMInterceptorChain): Promise<void> {
const info = chain.getRouterInfo();
const context = chain.getContext();
// ...
if (!!AppStorage.get('isLogin')) {
await chain.onContinue()
} else {
info.context.getPromptAction().showToast({ message: 'Please log in first.' });
HMRouterMgr.push({
pageUrl: 'loginPage',
skipAllInterceptor: true
});
await chain.onIntercept();
}
// ...
}
} The figure below shows the effect.

If an application has pages that consume resources greatly during initialization and need to be reused, you can use a singleton page. The video playback page in a video application is one of the typical service scenarios. This page requires video decoder resources and initialization, and this page frequently appears in the video application. To solve this problem, set the singleton parameter in the @HMRouter annotation to true.
@HMRouter({
pageUrl: 'liveHome',
singleton: true,
animator: 'liveInteractiveAnimator',
lifecycle: 'liveHomeLifecycle'
})
@Component
export struct LiveHome {
// ...
} In the HMRouter framework, set dialog of the @HMRouter annotation to true and then the current page can be used as a dialog box.
@HMRouter({
pageUrl: PageConstant.PRIVACY_DIALOG_DETAIL,
dialog: true,
// ...
})
@Component
export struct PrivacyDialogDetail {
// ...
} @HMRouter({ pageUrl: 'PayCancel', dialog: true,animator:'PayCancelDialog' })
@Component
export struct PayCancel {
// ...
build() {
Stack({ alignContent: Alignment.Center }) {
ConfirmDialog({
title: 'Cancel Order',
content: 'Are you sure you want to cancel the order?',
leftButtonName: 'No',
rightButtonName: 'Yes',
leftButtonFunc: () => {
HMRouterMgr.popAsync({
navigationId: this.queryNavigationInfo()?.navigationId
});
},
rightButtonFunc: () => {
// ...
}
});
}
.width('100%')
.height('100%')
.position({
x: '50%',
y: '50%'
})
.markAnchor({
x: '50%',
y: '50%'
});
}
} @HMLifecycle({ lifecycleName: 'ExitPayLifecycle' })
export class ExitPayLifecycle implements IHMLifecycle {
model: ObservedModel = new ObservedModel();
onBackPressed(): boolean {
HMRouterMgr.to('PayCancel')
.withParam(this.model.pageUrl)
.pushAsync()
return true;
}
} @HMRouter({
pageUrl: 'PayDialogContent',
dialog: true,
lifecycle: 'ExitPayDialog',
interceptors: ['LoginCheckInterceptor']
})
@Component
export struct PayDialogContent {
// ...
} The figure below shows the effect.

In this scenario, when a user performs the return operation for the first time, a toast "Return again to exit the app" is displayed. When performs the return operation for the second time, the user exits the application successfully. The procedure is as follows:
@HMLifecycle({ lifecycleName: 'ExitAppLifecycle' })
export class ExitAppLifecycle implements IHMLifecycle {
private lastTime: number = 0;
onBackPressed(ctx: HMLifecycleContext): boolean {
let time = new Date().getTime();
if (time - this.lastTime > 1000) {
this.lastTime = time;
ctx.uiContext.getPromptAction().showToast({
message: 'Go back and exit the application again',
duration: 1000
});
return true;
} else {
return false;
}
}
} The figure below shows the effect.

const globalPageTransitionEffect: IHMAnimator.Effect = new IHMAnimator.Effect({
direction: IHMAnimator.Direction.BOTTOM_TO_TOP,
opacity: { opacity: 0.5 },
scale: { x: 0.5, y: 0.2 }
}) After the definition is complete, import the instance to the dialogAnimator parameter of the HMNavigation component.
HMNavigation({
navigationId: 'mainNavigationId', homePageUrl: 'HomeContent', options: {
dialogAnimator: globalPageTransitionEffect,
}
}) const globalPageTransitionEffect: IHMAnimator.Effect = new IHMAnimator.Effect({
direction: IHMAnimator.Direction.BOTTOM_TO_TOP,
opacity: { opacity: 0.5 },
scale: { x: 0.5, y: 0.2 }
}) Import the created instance as a parameter to dialogAnimator.
HMNavigation({
navigationId: 'mainNavigationId', homePageUrl: 'HomeContent', options: {
dialogAnimator: globalPageTransitionEffect,
}
}) You can customize the animation class and implement the effect method in the IHMAnimator API. This method will pass the effect objects enterHandle and exitHandle as parameters. You can use the start or finish methods of the parameter objects to set the start and end states of the corresponding effect. The following common attributes are available as well:
The following sample code indicates that the entrance animation moves from bottom to the top of the screen at a linear speed for 400 ms and the exit animation moves from top to the bottom of the screen at a linear speed for 400 ms.
@HMAnimator({ animatorName: 'CustomAnimator' })
export class CustomAnimator implements IHMAnimator {
effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
// to animator
enterHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '100%' }).scale({ x: 0.7 }).opacity(0.3)
}).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '0' }).scale({ x: 1 }).opacity(1)
})
enterHandle.duration = 400;
enterHandle.curve = Curve.Linear;
// cut animator
exitHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '0' }).scale({ x: 1 }).opacity(1)
}).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '100%' }).scale({ x: 0.7 }).opacity(0.3)
})
exitHandle.duration = 400;
enterHandle.curve = Curve.Linear;
}
} After the custom animation is defined, the instance can be passed as the animator parameter of the new chainable page navigation API.
HMRouterMgr.to('ProductContent')
.withAnimator(new CustomAnimator())
.pushAsync() The figure below shows the effect.

The same page may have different transition effects in different situations. Take the comment page transition in the video playback page as an example.
Assumed that the comment component is enabled. The entrance and exit animation of comment page is defined as follows when video playback page is in portrait mode:
@HMAnimator({ animatorName: 'myAnimator1' })
export class MyAnimator1 implements IHMAnimator {
effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
enterHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '100%' })
}).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '0' })
})
exitHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '0' })
}).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ y: '100%' })
})
}
} The entrance and exit animation of comment page is defined as follows when video playback page is in landscape mode:
@HMAnimator({ animatorName: 'myAnimator2' })
export class MyAnimator2 implements IHMAnimator {
effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
enterHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ x: '100%', y: '0' })
}).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ x: 0 })
})
enterHandle.duration = 500;
exitHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ x: '0' })
}).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
modifier.attribute?.translate({ x: '100%' })
})
exitHandle.duration = 500;
}
} Finally, set animation effect based on the situation. For example, different animator values are used during page redirection based on whether the video is played in landscape mode.
@Component
export struct CommentInput {
// ...
build() {
Row() {
Image($r('app.media.icon_comments'))
.width(24)
.height(24)
.margin({ right: 16 })
.onClick(() => {
if (this.isLandscape) {
HMRouterMgr.to('liveComments')
.withNavigation(this.queryNavigationInfo()?.navigationId)
.withParam({commentRenderNode: ''})
.withAnimator(new MyAnimator2())
.onResult((paramInfo: PopInfo)=>{
this.videoWidth = '100%';
})
.pushAsync()
this.videoWidth = '50%';
} else {
HMRouterMgr.to('liveComments')
.withNavigation(this.queryNavigationInfo()?.navigationId)
.withParam({commentRenderNode: ''})
.withAnimator(new MyAnimator1())
.onResult((paramInfo: PopInfo)=>{
this.videoHeight = '100%';
})
.pushAsync()
this.videoHeight = '30%'
}
});
}
}
} The figure below shows the effect.

When an application has a requirement for synchronizing an entrance/exit effect of a page with a gesture operation of a user, that is, when a finger of the user moves on the screen, the page moves with the gesture of the user. In the following sample code, you can control the animation playback progress by calling interactive() of the IHMAnimator; determine whether to move rightward to perform the page return operation using actionStart; update the animation progress using updateProgress; obtain the final state of the animation using actionEnd to determine whether to continue the animation and return to the previous page.
@HMAnimator({ animatorName: 'liveInteractiveAnimator' })
export class LiveInteractiveAnimator implements IHMAnimator {
effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
// ...
}
interactive(handle: HMAnimatorHandle): void {
handle.actionStart((event: GestureEvent) => {
if (event.offsetX > 0) {
HMRouterMgr.popAsync();
}
handle.startOffset = event.fingerList[0].localX;
});
handle.updateProgress((event, proxy, operation, startOffset) => {
if (!proxy?.updateTransition || !startOffset) {
return;
}
let offset = 0;
if (event.fingerList[0]) {
offset = Math.abs(event.fingerList[0].localX - startOffset);
}
if (offset < 0) {
proxy?.updateTransition(0);
return;
}
let rectWidth = event.target.area.width as number;
let rate = offset / rectWidth;
proxy?.updateTransition(rate);
});
handle.actionEnd((event, proxy, operation, startOffset) => {
if (!startOffset) {
return;
}
let rectWidth = event.target.area.width as number;
let rate = 0;
if (event.fingerList[0]) {
rate = Math.abs(event.fingerList[0].localX - startOffset) / rectWidth;
}
if (rate > 0.4) {
proxy?.finishTransition();
} else {
proxy?.cancelTransition?.();
}
});
}
} The figure below shows the effect.

In this scenario, you want to preload the network request and execute the network request in other threads without blocking the main thread. The code implementation is as follows:
@Concurrent
async function networkRequest(lifecycle: string): Promise<string> {
// ...
} @HMLifecycle({ lifecycleName: 'requestLifecycle' })
export class ExampleLifecycle implements IHMLifecycle {
private requestModel: RequestModel = new RequestModel();
onPrepare(): void {
console.log(this.requestModel.data);
let task: taskpool.Task = new taskpool.Task(networkRequest, 'onPrepare');
taskpool.execute(task).then((res: Object) => {
console.log(res + '');
});
}
// ...
} 
In this scenario, the browsing history (such as the scroll position) persists even after the page is closed. A typical case is the comments section of a short video: when a user opens it, scrolls to a point, and then closes it, the comments will remain at that same scroll position upon reopening. The code implementation is as follows:
@Builder
function buildComment(liveComments: LiveCommentsProduct[]) {
// ...
}
export class CommentNodeController extends NodeController {
commentList: BuilderNode<[LiveCommentsProduct[]]> | null = null;
commentListData: LiveCommentsProduct[] = new LiveCommentsModel().getLiveCommentsList();
constructor() {
super();
}
makeNode(context: UIContext): FrameNode | null {
if (this.commentList === null) {
this.nodeBuild(context);
}
return this.commentList!.getFrameNode();
}
nodeBuild(context: UIContext) {
this.commentList = new BuilderNode(context);
if (this.commentList !== null) {
this.commentList.build(wrapBuilder<[LiveCommentsProduct[]]>(buildComment), this.commentListData);
}
}
dispose() {
if (this.commentList !== null) {
this.commentList.dispose();
}
}
} @HMLifecycle({ lifecycleName: 'liveHomeLifecycle' })
export class LiveHomeLifecycle implements IHMLifecycle {
commentRenderNode: CommentNodeController = new CommentNodeController();
// ...
onAppear(ctx: HMLifecycleContext): void {
this.commentRenderNode.makeNode(ctx.uiContext);
}
onDisAppear(ctx: HMLifecycleContext): void {
this.commentRenderNode.dispose();
}
} @Component
export struct CommentInput {
@StorageLink('changeVideoHeight') videoHeight: string | number = CommonConstants.FULL_PERCENT;
commentRenderNode: CommentNodeController = new CommentNodeController();
// ...
} 
If you need to collect statistics on the page loading duration or other custom dotting data, you can use the lifecycle callbacks to perform dotting at the corresponding position. The following example shows how to collect statistics on the page stay duration. The implementation is as follows:
@HMLifecycle({ lifecycleName: 'PageDurationLifecycle', global: true })
export class PageDurationLifecycle implements IHMLifecycle {
private time: number = 0;
onShown(): void {
this.time = new Date().getTime();
}
onHidden(ctx: HMLifecycleContext): void {
const duration = new Date().getTime() - this.time;
console.log(`Page ${ctx.navContext?.pathInfo.name} stay ${duration}`);
}
} 