How to use Impromptu as an confirm alert

116 Views Asked by At

I want to use Impromptu alert box as an confirm box when I reload my page. Right now I am using this normal javascript.

window.onbeforeunload = function(event) {
    return confirm("Confirm refresh");
};

However I no longer want to use this, so is there any chance to load Impromptu confirm box on page reload?

Thanks in advance

1

There are 1 best solutions below

0
Toonijn On

Short answer: no.

Long answer: Javascript is not possible to wait for a callback on (or before) unload. If the event returns the page will unload. With that in mind, a custom confirm-box will always need to wait for user interaction and this can't be blocking. So Impromptu (or any other plugin for that matter) will not be able to prevent the page from unloading. There is kind of an exception for native functions (like alert, confirm and even XMLHttpRequest...), those are or can be blocking so they can be executed on a pageunload.

The Mozilla docs teach us that modern browsers even prevent creating dialogs in window.onbeforeunload. If I test your function in chrome it creates a dialog:

Confirm navigation

false

Are you sure you want to leave this page?

The best you can do is something like:

window.onbeforeunload = function() {
    return "There is more to see on this site!";
};

This will create a box like:

Confirm navigation

There is more to see on this site!

Are you sure you want to leave this page?

The only way you can do something on page reload is after the page is reloaded, thus on the freshly requested page.

Note: I highly discourage using the onbeforeunload event, this bothers your users with an extra popup that they have to click before closing a page. I really dislike it when sites do that to me, it feels like spam.