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?
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. It might be better though to build a duplicate check into your database. That would catch accidental submissions using the "back" button as well.
Just check if there are values in the cache. If there was a back button then some saved values will still be there, and if the refresh button was clicked then everything will be the default.
When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With