4

In Vue component, I want to handle on browser back event like this:

mounted() {
  if ([browser back]) {
    console.log("browser back button clicked")
  } else {
    console.log("stay here")
  }
}

To handle browser back event, I found window.onpopstate function but I don't know how to put it inside the if statement.

Can you tell me what should I do on this case? Thank you!

1 Answer 1

5

You don't need to put inside an if statement. The event handler is sort of an "if statement".

See this example:

mounted() {
   // if back button is pressed
   window.onpopstate = function(event) {
     alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
   };
}
Sign up to request clarification or add additional context in comments.

2 Comments

But in not browser back case, how can i handle this?
When in normal mode (before back pressed) you can add any code to mounted then override it in onpopstate. Are you checking for hash changes in url?

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.