38

If the user refreshes the page in question it will add another record to the database, so I want to warn the user through an alert box if they really want to refresh the page and if they click ok then the page should be refreshed otherwise if they click cancel it won't be.

How to make this type of alert box appear when the browser's refresh button is clicked in a way that is cross browser compatible?

Faber
  • 395
  • 1
  • 4
  • 5

6 Answers6

65

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.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 1
    One question though, your message "Data will be lost if you leave the page, are you sure?" appears underneath another message in the alert box: "Are you sure you want to navigate away from this page" and underneath that appears the message "press continue to navigate away or cancel to stay on the current page". Is there any way to customize these 2 other messages as well? – Faber Jul 10 '10 at 23:20
  • @Faber - Not that I'm aware of...this is a per-browser thing that will vary, the `onbeforeunload` event is *very* non-standard. – Nick Craver Jul 10 '10 at 23:23
  • also I'm just speculating here, but would it be possible to detect page refresh by checking to see if the url that one goes to next matches the url of the present page, somehow with js? Because now if they user clicks on the homepage or some other page which won't add another entry to the db it still pops that message. – Faber Jul 10 '10 at 23:23
  • @Faber - There isn't a way to see the url you're going to, not in a generic way...if there was a way, websites could see where you're going when you're leaving them, say when you typed a new site in the address bar...you see how that quickly becomes a privacy issue, something you don't want to expose to script sites can run. – Nick Craver Jul 10 '10 at 23:26
  • @NickCraver Can we customized it, if we click on yes then the form will be submit Ex- : document.forms["myForm"].submit(); and onclick of No it stayed on same page... Please suggest me Link : http://stackoverflow.com/questions/34767942/how-can-i-restrict-page-loading-on-reload-option-browser –  Jan 13 '16 at 13:34
  • While click on **REFRESH ICON** in Chrome this is not working ... :( – Shurvir Mori Apr 06 '22 at 04:10
11

All the answers are quite old, as of today 2020, according to HTML specification, you can do it this way.

Important Note: Custom text is not supported in most of the browsers now. (it was supported in older browsers).

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});
prabhatojha
  • 1,925
  • 17
  • 30
  • 2
    yeah the accepted answer is not working on normal reload, works only on cache clear key combinations but your answer worked for normal reload as well – Firdous bhat Jan 13 '21 at 14:58
10

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.

Pierre
  • 8,397
  • 4
  • 64
  • 80
pkaeding
  • 36,513
  • 30
  • 103
  • 141
2

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.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
1

This is not possible. The best you can do is use the onbeforeunload event but that will fire on any event leaving the current page. It is not possible to target the refresh button specifically.

See e.g. this question on onbeforeunload

It might be better though to build a duplicate check into your database. That would catch accidental submissions using the "back" button as well.

An alternative would be using a random one-time token that gets built into the form. If two operations are attempted using the same token, you would stop it.

Community
  • 1
  • 1
Unicron
  • 7,275
  • 1
  • 26
  • 19
1

Quoting from official Mozilla site here, It is no longer supported to supply a custom message.

When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:

Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292). Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status).

Yogesh Kumar Gupta
  • 1,009
  • 1
  • 10
  • 10