0

So i implemented a back button that works similar to the browser back button. But i want it to be a disabled button if the next click would leave the site (idc about the browser button mind you). Is there any way to check if going back further would leave the site or at least warn the user they are about to leave? right now i have this and i'm using Vue.js:

<div @click="goBack"></div>

    goBack: function () {
      this.$router.go(-1)
    }
  • Does this answer your question? [How to check if the user can go back in browser history or not](https://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not) – dh4ze Jan 21 '21 at 08:20
  • well the thing is, i just dont want the user to leave through the means of my own website. if they use the browser back button they should still be able to get back to their google search – struppi441 Jan 21 '21 at 08:28

1 Answers1

0

You can use window.history.length to track if history stack still has item(s) (length > 0). However this approach only work when user start afresh from a new tab/window. If a user uses existing tab with some browsing history, this method will not work.

The other way you can do is to mimic the history stack for your own app using sessionStorage. Whenever user navigate to a new page, you will push a record in sessionStorage. And when user click your back button you will pop the a record from sessionStorage. So you can check the sessionStorage is empty and a click to back button will trigger an alert or some sort.

HW Siew
  • 973
  • 8
  • 16
  • okay so I solved it by putting a counter into the state. So every time if the user presses a button that will change the site, this counter goes up by one and everytime the user presses the back button it counts down by one. The back button is disabled if the counter is 0. This works as long as the user doesnt navigate through the Browser implemented back and forward buttons. – struppi441 Jan 26 '21 at 08:50