How to get the current active page name as a string on any given time from Navigation?

Hello! For PageControl there’s ActiveIndex in order to get the current page in view (via Observable), but how can this be done with Navigator? In the example below I could get the current page by using a global string variable and changing it in router.push (or Activated for every page) and OnGoBack, but that’s more work than simply getting it straight from the UX via Observable for example.

<App>
  <JavaScript>

    module.exports = {
      gotoGreenPage: function() {router.push("greenPage");},
      gotoRedPage: function() {router.push("redPage");},
      logCurrentPath: function() {
        console.log("Current path: ?");
      }
    };

  </JavaScript>
  <Router ux:Name="router" />
  <Navigator ux:Name="navigator" DefaultPath="yellowPage">
    <Page ux:Name="yellowPage" Background="Yellow">
      <Button Text="Goto green page" Background="Black" Width="200" Height="100" Alignment="Center" Y="-25%" Clicked="{gotoGreenPage}" />
      <Button Text="Log current path" Background="Black" Width="200" Height="100" Alignment="Center" Clicked="{logCurrentPath}" />
      <Button Text="Goto red page" Background="Black" Width="200" Height="100" Alignment="Center" Y="25%" Clicked="{gotoRedPage}" />
    </Page>
    <Page ux:Name="greenPage" Background="Green">
      <Button Text="Log current path" Background="Black" Width="200" Height="100" Alignment="Center" Clicked="{logCurrentPath}" />
    </Page>
    <Page ux:Name="redPage" Background="Red">
      <Button Text="Log current path" Background="Black" Width="200" Height="100" Alignment="Center" Clicked="{logCurrentPath}" />
    </Page>
  </Navigator>
</App>

Perhaps router.getRoute() could be of help?

Thanks again Uldis!

Hello! I’m trying to use getRoute in OnBackButton with a Handler, but the problem is that when that Handler fires, getRoute returns the page which we are about to show. Is there a way to get the previous page instead of the upcoming?

I don’t think so, because your getRoute call happens after the back button was pressed, so the navigation action has already happened.

Can’t help but ask: why do you need this?

I’m trying to detect the following:

  1. User is in the yellowPage (the main page).
  2. User taps the back button.
    In this case the app should close on Android (using a custom Uno class for this). The problem is that if I’m in green or red page and press the back button, OnBackButton handler returns also the yellowPage from the router. One solution could be that I create a global string variable “previous_page” and change this in Activated.

You could create a global shouldClose or canGoBack boolean, and change the value of it from the Activated trigger on whatever pages it’s appropriate. Or use WhileCanGoBack, optionally, with Invert="true".

Thanks Uldis!