I am using the function
window.onbeforeunload = function(){
if(sessionStorage.hasOwnProperty("teststatred")){
validNavigation = true;
leave_message = "You are in the middle of the test, Are you sure do you want to close the window?"
}
if (validNavigation)
{
if (!e) e = window.event;
e.cancelBubble = true;
e.returnValue = leave_message;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
return leave_message;
}
}
This function will display a window of two buttons: Leave this page
and Stay on this page
.
How can I execute a function when the user clicks on Leave this page
or 'Stay on this page'?
Unfortunately, you cannot, because the only way would be to use
confirm(), alert(), or prompt()
and they will all be ignored:'Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.'
https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload
However, it does say may, so it wouldn't hurt to give it a try and
prompt
something.