Search code examples
javascriptvue.jsbackpreventdefault

vuejs run function after click back button in browser


I load a component inside my vuejs page which is only visible after a certain button is pressed. But if the usere uses not the BACK BUTTON from the BROWSER, it doen't close my component and maked the "original" component visible, it jumes back to the page before.

I need to prevent this behaviour. What I want to do is:

  1. Stop the "GO BACK" action
  2. Run a function instead

I tried the following already and it runs the function when someone clicks the "BACK BUTTON" in the browser but it doesn't prevent the "GO BACK ACTION".

mounted() {
    window.onpopstate = () => {
      this.closeDetailedView()
    }
  },

The closeDetailedView function does the folowing:

closeDetailedView() {
  this.$emit('closeDetailedView')
},

Can someone help me?

thanks


Solution

  • You can use the event listener to do what you want and use history.pushState to "overwrite" the state to your current one!

    history.pushState(null, null, document.URL);
    window.addEventListener('popstate', function () {
        history.pushState(null, null, document.URL);
    });
    

    The event listener will detect when the user clicks the button.

    If you want to keep your current code

    window.onpopstate = () => {
      history.pushState(null, null, document.URL);
      this.closeDetailedView();
    }