DEV Community

HarmonyOS
HarmonyOS

Posted on

How to Replace the Previous Page Using NavPathStack?

Read the original article:How to Replace the Previous Page Using NavPathStack?

Question

After loading the home page following the startup page, I need to replace the startup page. However, using the NavPathStack.replaceByName method does not work — pressing the back key on the home page still returns to the startup page.
How can I prevent this and make the app minimize instead of returning to the startup page?

Short Answer

The startup page (the first page of the Navigation stack) is not actually part of the navigation stack, so it cannot be replaced using NavPathStack.replaceByName.
If you want the home page to minimize the application directly — instead of returning to the startup page when pressing the back key — you can implement the minimize function using the win.minimize() API.

This ensures that pressing the back button from the home page sends the app to the background rather than navigating back to the startup page.

Reference Code:

build() {
  NavDestination() {
    // ...
  }
  .onBackPressed(() => {
    try {
      window.getLastWindow(getContext(this), (err: BusinessError, win) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error(`Failed to obtain the top window. Cause code: ${err.code}, message: ${err.message}`);
          return;
        }
        win.minimize((err: BusinessError) => {
          const errCode: number = err.code;
          if (errCode) {
            console.error(`Failed to minimize the window. Cause code: ${err.code}, message: ${err.message}`);
            return;
          }
          console.info('Succeeded in minimizing the window.');
        });
        console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(win));
      });
    } catch (exception) {
      console.error(`Failed to obtain the top window. Cause code: ${exception.code}, message: ${exception.message}`);
    }
    return true;
  })
}
Enter fullscreen mode Exit fullscreen mode

Applicable Scenarios

  • When the startup page should not remain in the navigation history after loading the main home page.
  • For applications that need to exit or minimize when users press the back button on the home screen.
  • In cases where Navigation stack replacement methods (replaceByName, etc.) do not remove the startup page.

Written by Emine INAN

Top comments (0)