简体   繁体   中英

Custom JavaScript alert not stopping page from closing

I'm using the custom alert below when page is about to close. The issue is that the alert pups up and the page closes before the user can click the OK button on the custom alert. What is missing is the custom alert that it cannot keep the page open till the user clicks the OK button?

window.onbeforeunload = function() {
   {
      return custom_alert(head, txt);
   }


function custom_alert(head, txt) {
  var d = document;
  var c_obj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
  c_obj.id = "contain";
  c_obj.style.height = d.documentElement.scrollHeight + "px";
  var alertObj = c_obj.appendChild(d.createElement("div"));
  alertObj.id = "alert";
  if (d.all && !window.opera)
    alertObj.style.top = document.documentElement.scrollTop + "px";
  alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
  alertObj.style.visiblity = "visible";
  var h1 = alertObj.appendChild(d.createElement("h1"));
  h1.appendChild(d.createTextNode(head));
  var msg = alertObj.appendChild(d.createElement("p"));
  msg.innerHTML = txt;
  var btn = alertObj.appendChild(d.createElement("a"));
  btn.id = "close";
  btn.appendChild(d.createTextNode('ok'));
  btn.focus();
  btn.onclick = function() {
    c_obj.parentNode.removeChild(c_obj);
  };
  alertObj.style.display = "block";
}

I found a library that solves this problem:

http://t4t5.github.io/sweetalert/

The offical alert: alert("Oops... Something went wrong!");

The changed alert: sweetAlert("Oops...", "Something went wrong!", "error");

This library solves many of the problems of creating your own alert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM