1

I'm using SweetAlert on all my pages and I want to be able to use that in order to preserve the consistency of style on my site whenever the user tries to leave the page with unsaved changes.

The problem I have is that I can't figure out how to prevent the user from leaving without using the default (browser controlled) alert. The code below does show the sweet alert dialog for a split second before going off to whatever page the user clicked on. I just want to use my own dialog instead of the ugly browser controlled alert dialog which is different on every browser.

I've already read this post which is 14 years old. I can't believe it's 2022 and the answer is still "you can't". There has to be a way, right??

Here's the code I'm using. The recordIsDirty flag is handled elsewhere and is working perfectly.

const allowPageUnload = function (event) {
    console.log("ok bye");
    event.preventDefault(); 
    delete event['returnValue'];
}

const rejectPageLeave = function (event) {
    console.log("the leave event was rejected");
    event.preventDefault();
    event.returnValue = undefined;
}

const confirmLeaveIfDirty = async function (event) {

    event.preventDefault();

    if (recordIsDirty) {
        await Swal.fire({
            icon: 'warning',
            title: "Unsaved Changes!",
            html: "You have unsaved changes. Are you sure you want to leave without saving? All changes will be lost.",
            showCancelButton: true,
            confirmButtonText: "Yes, Cancel Changes",
            cancelButtonText: "No, Stay Here"
        }).then((result) => {

            if (result.isConfirmed) {
                allowPageUnload(event);
            }
            else {
                rejectPageLeave(event)
            }
        })
    }
    else {
        allowPageUnload(event);
    }
}

$(document).ready(function () {
    window.addEventListener('beforeunload', function (event) {
        confirmLeaveIfDirty(event);
    });
}
JakeMc
  • 413
  • 6
  • 13
  • Unfortunately, [How can I override the OnBeforeUnload dialog and replace it with my own?](https://stackoverflow.com/q/276660/18364330) has the correct answer, just not the one you were hoping for. If browsers allowed you to implement independently, then it would be an abuse-vector for sites that never allowed you to leave. – Socko Mar 18 '22 at 17:32

0 Answers0