0

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

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Vanishdark, worked perfectly!! I used it the following way in the mounted hook history.pushState(null, null, document.URL) window.addEventListener('popstate', () => { //history.pushState(null, null, document.URL) this.closeDetailedView() })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.