Reputation: 25259
This is my scenario: A user start editing a post, upload a photo, but then he closes the browser, or jump to a different page.
I want to be able to delete the photo uploaded and warn the user of the consequnces.
I know there is a function window.onbeforeunload But I'm not sure if I get it right
window.onbeforeunload = askExit;
function askExit(){
return "Are you sure you want to exit this page?";
}
Now, how do I capture the button press "leave this page" So I can fire a second function to clean the session, photos, etc?
Upvotes: 2
Views: 72
Reputation: 12367
Well, in theory, you can't:
The primary purpose for the beforeunload is for things like allowing the users the option to save changes before their changes are lost.
However, you could technically do this with a bit of onfocus
/onunload
wizardry:
var isFromUnloadDialog = false;
window.addEventListener("beforeunload", function() {
isFromUnloadDialog = true;
return "Are you sure you want to exit this page?";
});
window.addEventListener("focus", function() {
if (isFromUnloadDialog) {
// User canceled the unload
isFromUnloadDialog = false;
}
});
window.addEventListener("unload", function() {
// User didn't cancel the unload; clean up
});
This also may be worth a read if you haven't taken a look at it already.
Upvotes: 1