1

I am trying to alert the user when using the browser back button to save their changes. I am currently using the 'popstate' event listener, which works well, however once the user has confirmed the message to say they're about to leave the page, if they press the browser forward arrow they are presented with the same confirm message which is misleading.

Is there any way to only use this on the browsers back button?

Below find my current code (I am also using React hooks for this)

Thanks!

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

  useEffect(() => {
    window.addEventListener('popstate', function (event) {
      if (event.state) {
        confirm("Do you want to leave this page?");
      }
    }, false);
  }, [])
mark
  • 235
  • 3
  • 11

0 Answers0