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.
-
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 Answers
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
orlodash.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.

- 5,109
- 2
- 32
- 41
-
I updated my answer with some additional possible issues you may encounter. – Marc Jun 13 '20 at 12:23
-
2History 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
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();
}
-
1
-
The property returns at least 1, because the list includes the current page. https://www.w3schools.com/jsref/prop_his_length.asp – Aftab Alam Jan 27 '23 at 11:33