Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 402
Faber Avatar asked Jul 10 '10 23:07

Faber


People also ask

How do you pop up an alert box when the browsers refresh button is clicked?

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.

How do I know if my refresh button is clicked?

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.

How do I know if my browser is refreshing or closing?

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.


1 Answers

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.

like image 200
Nick Craver Avatar answered Sep 22 '22 09:09

Nick Craver