Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about this:

$( window ).bind( 'beforeunload' , function( event ) {
    setTimeout( function() {
        alert( 'Hi againe!' );
    } );
    return '';
} ).bind( 'unload', function( event ) {
    alert( 'Goodby!' );
} );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...