Is there any way to cancel unload () or OnBeforeUnload ()?

1

Is there any way to cancel unload () or OnBeforeUnload ()? Something like this:

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 place

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

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

    
asked by anonymous 09.03.2016 / 21:45

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 could kill the process if he wanted and this would not fire onbeforeunload .

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

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

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

I basically replied here: Run script js when trying to close the window

A detail onbeforeunload is not used to detect closure or return only, it is used to detect any unloading of the current page, read more in this response: link

Another thing, break; is not used for this, it is used for loops like for , while and switch , it does not for loop events only. >     

09.03.2016 / 21:52