Вопрос

I just want to show a message before leaving the page, but my code doesn't works:

window.onload=function(){
    alert("Page with a digital clock");
    setInterval(clock,1000);
}

window.onbeforeunload=function(){
    alert("Are you sure to leave this page?");
}

The "onload alert" works fine, but the second is not working..

Это было полезно?

Решение

You can't put an alert inside onbeforeunload. Most browsers will do this for you so you don't need to handle it, you need to return the confirm message to the method instead:

window.onbeforeunload=function(){
    return "Are you sure to leave this page?";
}

Here are the docs for the method on MDN.

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top