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

后端 未结 5 1223
面向向阳花
面向向阳花 2020-12-09 08:16

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 pag

5条回答
  •  不知归路
    2020-12-09 09:03

    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.

提交回复
热议问题