1

Hello and thank you for your time!

I was learning by following a React course: https://app.pluralsight.com/library/courses/react-flux-building-applications/table-of-contents

And it looks like the React Router API has changed a lot since the course was filmed.

In the course it is taught how to use willTransitionFrom and willTransitionTo which both look like they are deprecated:https://github.com/ReactTraining/react-router/issues/1388

I would like to follow along, and I have tried to do the detect if the user is going to leave the current page. I have done:

  window.addEventListener('beforeunload', (event) => {
    if (!(window.confirm("DO YOU really want to exit a fun page like this?"))) {
        event.preventDefault();
    }
});

And also:

window.onbeforeunload = (event) => {
        if (!(window.confirm("DO YOU really want to exit a fun page like this?"))) {
            event.preventDefault();
        }
    };

It looks like neither of them gets fired, because I would like to show the confirm dialog when you try to load another page.

I have read: How to check if user is refreshing the page or navigating to other page How to display a pop up, when a user tries to leave the current page? https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Thank you for your help.

Yone
  • 2,064
  • 5
  • 25
  • 56
  • 2
    It is fired, but you didn't read the docs: "_NOTE: To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all." and "_Various browsers ignore the result of the event and do not ask the user for confirmation_" – Teemu Feb 13 '18 at 10:09

1 Answers1

0

Try this one (picked from https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
  return confirmationMessage;              // Gecko, WebKit, Chrome <34
});
Danny
  • 682
  • 1
  • 11
  • 21