Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda