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

后端 未结 5 1221
面向向阳花
面向向阳花 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:01

    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.

提交回复
热议问题