vuejs / router

🚦 The official router for Vue.js
https://router.vuejs.org/
MIT License
3.91k stars 1.19k forks source link

Add local history count on install to determine it is safe to go back #1996

Closed Soviut closed 1 year ago

Soviut commented 1 year ago

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

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.

const goBack = () => {
  if (router.historyLength > 1) {
    router.go(-1)
  }
}

And the same could be used in the template to disable or hide the button

<button v-if="router.historyLength > 1" @click="goBack">Go Back</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.

posva commented 1 year ago

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