2

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?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Francesco
  • 24,839
  • 29
  • 105
  • 152
  • 2
    `window.onunload = function(){ console.log("unloaded"); }` when "leave this page" is clicked, page unloads. But be careful, everything (dom, ajax calls etc) will be cleaned up. – gp. Mar 03 '15 at 02:37
  • 1
    Also see this the answer to this question. It used jQuery, but the principles are the same. http://stackoverflow.com/questions/11057224/jquery-prompt-to-save-data-onbeforeunload/11057949#11057949 – Jamey Mar 03 '15 at 02:43

1 Answers1

1

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.

Community
  • 1
  • 1
AstroCB
  • 12,337
  • 20
  • 57
  • 73