0

I want to catch the back event in javascript, react js and show an alert message before changing the route.

I managed to catch the event wit onpopstate, but the route is changed and I want to prevent changing the route until the alert is confirmed:

window.addEventListener("popstate", (ev) => {
      ev.preventDefault(ev);
      alert("Are you sure")
}) 

Also tried with react-route, I found here some examples, but none of them worked.

import { browserHistory } from 'react-router';

componentDidMount() {
    super.componentDidMount();

    this.onScrollNearBottom(this.scrollToLoad);

    this.backListener = browserHistory.listen(location => {
      if (location.action === "POP") {
        // Do your stuff
      }
    });
  }

componentWillUnmount() {
    super.componentWillUnmount();
    // Unbind listener
    this.backListener();
}

It behaves as in the first case, it doesn't prevent the back event.

fool-dev
  • 7,671
  • 9
  • 40
  • 54
georgiana_e
  • 1,809
  • 10
  • 35
  • 54

0 Answers0