1

In my PWA I'm implementing back and forward navigation buttons for when the app is in standalone mode. To achieve this I am injecting the Location service in my component and then:

public onForward() {
 this.location.forward();
}

public onBack() {
  this.location.back();
}

What I'm trying to do now is disable the forward button when there is no forward navigation available, and similarly disable the back button when there is no backward navigation available (e.g. app just launched). Any idea how to achieve this? The Location API doesn't seem to cater for this requirement.

Ahmad Akra
  • 505
  • 4
  • 14

1 Answers1

2

Yes, it seems quite clear indeed from the API docs.

You could simply follow that by yourself with a counter:

private history_depth = 0;

public onForward() {
  this.history_depth -= 1;
  this.location.forward();
}

public onBack() {
  this.history_depth += 1;
  this.location.back();
}

public isBackEnabled() {
  return this.history_depth > 0;
}

Edit:

However, it won't be perfect: manually going back through the browser will not work. This is explained in this SO post (tldr; not possible because would be a security issue), where it is advised to leave the Back button enabled - and it's a no-op if there is no back history.

Also, maybe there is something to work out with the history API. It won't be perfect, but maybe there are a few cases to work out successfully. You can see examples in the various answers of the mentioned SO post.

Qortex
  • 7,087
  • 3
  • 42
  • 59
  • 1
    My custom back and forward buttons are not the only way that the history depth can change. Another way is if the user goes from one screen to another, or if the user clicks the forward and back buttons of the browser itself or hits Alt-Left Arrow etc.. Trying to keep track manually of all the possibilities to maintain such a counter is extremely messy. Are we sure there is no clean and simple API somewhere to know if back or forward are available? – Ahmad Akra Mar 05 '19 at 07:53
  • yeah true, you would have to intercept events I guess, and update the counter. Sorry I replied too quickly. After looking up a bit, I updated the answer. Seems like it's not possible to have that fully working. – Qortex Mar 05 '19 at 08:05