Is there a way to cancel Unload() or Onbeforeunload()?

Asked

Viewed 499 times

1

Is there any way to cancel Unload() or Onbeforeunload()?
Something like that:

window.onbeforeunload = function(){
//ação aqui
break; //cancela o fechamento da pagina sem exibir nenhum alert
}

I need to open a div (popup) when the user clicks close or back, the idea was to put

document.getElementById('minhaDiv').style.display = 'block';

before the break, but this is not right because the break does not work and the page is closed. I hope to understand a little this salad!

1 answer

1

It is not possible to cancel and even if it were possible it would not be 100% safe, for example the user can kill the process if he wants and this would not trigger the onbeforeunload.

The "maximum" you can do is ask the user if they really want to close, like this:

window.onbeforeunload = function(){
    return "Deseja mesmo sair?";
};

If it were possible to do without the "Alert" (dialog) it would be the same as you control the user’s machine and really nobody wants it right?

That’s basically what I answered here: Run script js when trying to close the window

A detail the onbeforeunload is not used to detect closure or return only, it is used to detect any download of the current page, read more in this reply: /a/80707/3635

One other thing, the break; is not used for this, it is used for loops like for, while and in switch, it does not for events executions only looping cycles.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.