How to pop up an alert box when the browser's refresh button is clicked?

You can do it like this:

window.onbeforeunload = function() {
  return "Data will be lost if you leave the page, are you sure?";
};

This would show a prompt to the user allowing them to cancel. It's not refresh specific, but for your purposes (like editing a question on SO) that doesn't seem to matter, it's loss of info no matter where you're leaving to.


There isn't a way to tie it to just the refresh action, but you may want to look into window.onbeforeunload. This will allow you to run a function that returns a string just before the page is unloaded. If this string is not empty, then a popup confirmation dialog, containing this string and some other boilerplate text provided from the browser.

For example:

window.onbeforeunload = function () {
    if (someConditionThatIndicatesIShouldConfirm) {
        return "If you reload this page, your previous action will be repeated";
    } else {
        //Don't return anything
    }
}

Also, if the current page was loaded via a POST operation, then the browser should already display a confirmation box when the user tries to refresh it. As a general rule, any action that changes the state of the data on the server should be done through a POST request, rather than a GET.


There are two possible ways forward with this, both quite different.

One way would be to have an event handler bound to onbeforeunload event so that you can detect when the user is browsing away from the current page. If my memory serves me correctly however, onbeforeunload is not consistent across browsers (I don't think Opera responds to it IIRC, but have no way to currently test). Of course, this solution fails if the user turns off JavaScript.

The second and more robust way would be to implement the Post Redirect Get pattern which when used, prevents the data from being posted again when a user refreshes the page.

Tags:

Javascript