How to prevent the user from leaving the page when there is an API call in progress

Pretty much as the title says, I want to prevent the user from either

  1. Closing the tab
  2. Redirecting to another page within my website
  3. Redirecting to another website

I have tried this in my router.beforeEach()

if (isLoading) {

    const answer = window.confirm(

      "Do you really want to leave? you have unsaved changes!"

    );

    if (answer) {

      next();

    } else {

      next(false);

    }

  } else return next();

but sadly this behavior doesn’t work in case the user closes the tab or redirects to a different website,
something to note is that, this isLoading variable is a variable from a getter in my store that gets whether there is loading or not. I would love it if anyone could help thanks!

Thanks!

This is usually handled by listening for the beforeunload event from the window object. From there, you can check to see if something is currently loading and then ask the user if they really want to leave or not. Returning anything other than undefined will prevent the user from leaving. You can see an example from the MDN link above.

This will check if the user is trying to close the tab or leave. This, in addition to your router check, should do the trick.

A StackOverflow thread on the issue: javascript - Warn user before leaving web page with unsaved changes - Stack Overflow

Why not try it in another way? You can just create a full-screen dialog to reminder the user that a API calling is being handled when it begins and drop it when the proceeding ends. Then the user can choose to leave the page or not beforehand.