Search code examples
javascriptdialogsweetalert2

Prevent SweetAlert2 from closing/dismissing from willClose?


Sorry if I am missing something from the documentation but I can't find anyway to prevent a dialog from closing in SweetAlert 2, these won't work:

        await Swal.fire({
            html: diagHtml,
            showCancelButton: true,

            willClose: (el) => {
                console.log(el);

                if (someLogic()) {
                    event.preventDefault();
                    return false;
                }
            },
        });

Is there a way to keep the dialog stay, preferably with async?


Solution

  • No, you can't prevent dialog from closing with willClose, maybe the following code can be your alternative:

    await Swal.fire({
      html: diagHtml,
      showDenyButton: true,
      allowOutsideClick: false,
      allowEscapeKey: false,
      preConfirm: () => {
        if (someLogic()) {
          return false; // Prevent confirmed
        }
      },
      preDeny: () => {
        if (someLogic()) {
          return false; // Prevent denied
        }
      },
    });