11

I am using $router.go(-1) to go back to the previous page but as I am using this on a home page I want know how to check if there is a previous route.

xlm
  • 6,854
  • 14
  • 53
  • 55
selam
  • 113
  • 1
  • 1
  • 8
  • Related: https://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not – xlm Oct 12 '21 at 05:17

2 Answers2

14

Vue router navigation is tracked by the native browser history, use window.history.length.

If it is 0 there is nothing to go back to.

However; Users arriving from another website have a value higher than 0.

To overcome this issue, upon your App mounting; store the initial value of window.history.length globally.

Capture the initial value using a mount hook such as: beforeMount or mounted.

Store the history length value using $root as a global state:

this.$root.historyCount = structuredclone(window.history.length)

Alternatively use VueX if you are already leveraging the store bus plugin.

structuredclone or lodash.clone ensures you have a copy of the value rather than a reference to it, a reference would be bad; as this means you would always have the latest history count rather then the original entry point value.

https://developer.mozilla.org/en-US/docs/Web/API/structuredClone https://lodash.com/docs/4.17.15#clone

When checking history state on a call to action, subtract $root.historyCount from window.history.length to see if zeroes out.

This way you will be only counting the history that occurs in your own app.

You may also want to consider that perhaps if your current route ($router.currentRoute) is the home page there is also no way of going back beyond that page but obviously will prevent back navigation to prior home revisits.

Marc
  • 5,109
  • 2
  • 32
  • 41
  • I updated my answer with some additional possible issues you may encounter. – Marc Jun 13 '20 at 12:23
  • 2
    History length seems to be capped at 20 (at least in Chrome) so this doesn't always work. Also, cloning isn't necessary because the length is a primitive. – Indiana Kernick Feb 01 '23 at 01:03
0

As window.history.length will always return 1. You can use

if (window.history.state.back === null) {
 router.push({path="/"}); //or whichever path you required
} else {
 router.back();
}