I have a 404 page that I want to add a friendly "go back" button to. I could naively use
router.go(-1)
This would work for a broken internal link, taking them safely back to the internal page they came from.
However, this would not work if they arrived there from an external link (say from an email or posted on another site). In that case the bahviour will be unpredictable, potentially causing the user to return to the previous site or their browser's home screen.
I want to know if it's safe to go back.
Proposed solution
When the router installs on page load have it store the current window.history.length. This value can then be subtracted from the history length to determine how many times the router has updated the history locally within the site.
This local history count could then be exposed in the API. Making it possible to determine if there is any local history to go back to.
I could build this functionality into a simple plugin that has something like a useHistoryLength composable. However, it makes way more sense as part of the router.
This is intentionally left out of router core. As you mentioned, it can be implemented in user land. One can write to the history state on router.isReady() and read it from history state
What problem is this solving
I have a 404 page that I want to add a friendly "go back" button to. I could naively use
This would work for a broken internal link, taking them safely back to the internal page they came from.
However, this would not work if they arrived there from an external link (say from an email or posted on another site). In that case the bahviour will be unpredictable, potentially causing the user to return to the previous site or their browser's home screen.
I want to know if it's safe to go back.
Proposed solution
When the router installs on page load have it store the current
window.history.length
. This value can then be subtracted from the history length to determine how many times the router has updated the history locally within the site.This local history count could then be exposed in the API. Making it possible to determine if there is any local history to go back to.
And the same could be used in the template to disable or hide the button
Describe alternatives you've considered
I could build this functionality into a simple plugin that has something like a
useHistoryLength
composable. However, it makes way more sense as part of the router.