Capturing result of window.onbeforeunload confirmation dialog

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.

window.onbeforeunload confirmation dialog

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:

jQuery AJAX call in onunload handler firing AFTER getting the page on a manual refresh. How do I guarantee onunload happens first?

12
задан Community 23 May 2017 в 11:46
поделиться