Is there a way to capture to result of the window.onbeforeunload
confirmation dialog like the one below from Stack Overflow (this happens when leaving the 'Ask Question' page without posting the question)?
This is how it appears in Chrome, I believe it's slightly different in other browsers, but you always have some form of yes/no buttons.
Presumably if they're still on the offending page after the event has been triggered they chose to stay and you could probably figure this out by watching the sequence of js. However I would like to know how to determine if they clicked "Leave this page"?
I've implemented this like below:
// concept taken from SO implementation
function setConfirmUnload(showMessage, message) {
window.onbeforeunload = showMessage ? (message ? message : "this is a default message") : null;
}
// pseudo code
listen to changes on inputs
if any inputs fire a change event
call setConfirmUnload(true, 'My warning message')
note I'm using jQuery within my site.
I'm essentially trying to implement a Gmail like drafting implementation, wherein if a user leaves a page with a form they've made changes to without saving they're warmed with a similar dialog. If they choose to discard they're changes and leave the page, I need to clean up some temporary records from the database (I'm thinking an AJAX call, or simply submitting the form with a delete
flag) then sending them on their way.
My question also relates to:
window.onfocus()
. That function will be triggered when the user clicks on STAY, and is returned to the page. However, note that onfocus() will also be triggered when changing tabs, windows etc. Set a global variable in onbeforeunload() to be able to check/capture from where the user is coming. If the user DOES want to leave the page, you can do some final stuff inwindow.onunload()
– Kinetic