Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
How do I use a custom confirmation method when window.onbeforeunload happens

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);
    });
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!