单击 Swal 取消按钮时重定向,但在 Swal 外部单击时不重定向

Redirect when clicked on Swal cancel button but not when clicked outside of Swal

我尝试使用 result.dismissresult.isDismissedresult.isDenied,但我似乎无法足够具体地检查用户是否在 swal 消息之外单击. 这是我的代码:

Swal.fire({
  position: "top-end",
  title: `${name} successfully added to cart!`,
  icon: "success",
  showCancelButton: true,
  cancelButtonText: "Continue shopping",
  cancelButtonColor: "green",
  confirmButtonText: "Go To Cart",
  confirmButtonColor: "blue",
}).then((result) => {
  if (result.isConfirmed) history.push("/cart");
  else if (location.pathname == "/" && !result.dismiss)
    history.push("/products");
});

谢谢!

您可以通过检查结果 .dismiss 原因是否等于 Swal.DismissReason.cancel:

来检查警报是否已使用取消按钮解除

Swal.fire({
  position: "top-end",
  title: "Item successfully added to cart!",
  icon: "success",
  showCancelButton: true,
  cancelButtonText: "Continue shopping",
  cancelButtonColor: "green",
  confirmButtonText: "Go To Cart",
  confirmButtonColor: "blue",
}).then((result) => {
  if (result.dismiss === Swal.DismissReason.cancel) {
    console.log("Redirect for cancel");
  } else {
    console.log("Redirect for non-cancel dismissals");
  }
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>