JavaScript Close Alert Box

Javascript close alert box

As mentioned previously you really can't do this. You can do a modal dialog inside the window using a UI framework, or you can have a popup window, with a script that auto-closes after a timeout... each has a negative aspect. The modal window inside the browser won't create any notification if the window is minimized, and a programmatic (timer based) popup is likely to be blocked by modern browsers, and popup blockers.

How to auto close Alert boxes

You can not close an alert box, just you can hijack window.alert

window._alert = window.alert;
window.alert = function () {
};

The code would have to appear before the third party library's code. What this means is, if you want to use an alert, you would have to change your code.

One way would to call the method that has the reference

window._alert("hi");

Other way would be to overload the "new" function

window._alert = window.alert;
window.alert = function (msg, showItNow) {
if (showItNow) {
window._alert(msg);
}
};
window.alert("BOOOO!"); //I will not show up
window.alert("hi", true); //I will show up

Programmatically close alert() in Javascript

As far as I know you cannot close the javascript's alert(); by code. You can try to use alternative notification method like modal window or something (so then if user is back online you can simply use jQuery function to hide/remove the modal box).

How to close the current window in browser after clicking ok in the alert message?

Just put the statements one after each other :

alert("ok");
window.close();

EDIT following Ankit's remark to OP : note that if you didn't open the window with Javascript yourself, you may not be authorized to close it depending on the browser.

How can I auto hide alert box after it showing it?

tldr; jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}

Use this like this:

tempAlert("close",5000);

Autoclose alert

jsFiddle Demo

This functionality is not possible with an alert. However, you could use a div

function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}

Use this like this:

tempAlert("close",1000);

closing a confirm or alert box with escape prevents fields to be accessed (chrome,edge)

confirmed bug as per https://bugs.chromium.org/p/chromium/issues/detail?id=1085949#c3

closing this issue.



Related Topics



Leave a reply



Submit