Show confirmation message before closing the page in JavaScript

- Andrés Cruz

En español

Many times we have asked ourselves if it is possible to show a confirmation window or alert when a user is leaving our page. This is particularly useful in various situations where the user is downloading or uploading a document on the page and it is essential that the user not close the page, that is, keep the session until the operation ends, and in these cases, we can show a confirmation message, we can easily implement this using the JavaScript beforeunload event that is executed when the user tries to close the window of our application.

The beforeunload event is executed just when the user tries to leave the page, that is, closes the browser window or the tab. In these cases, we can show a confirmation message to ask if the user is completely sure that they want to leave our page. application, however, is a tool that must be used carefully to avoid bothering the user with popups or pop-up messages.

Use

Its use is very simple, we simply have to assign some value to the returnValue property, usually it is simply a text and this text will be displayed when the user tries to close the page, if a value is not set, the event occurs, but it is not shows no alert or notification to the user that they are about to close the page.

Here you can see an example of its use:

window.addEventListener("beforeunload", function (event) {
 event.returnValue = "Are you sure you want to go out?"; 
});

window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Are you sure you want to go out?';
    }

    // For Safari
    return 'Are you sure you want to go out?';
};
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.