Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda