문제

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