1

I apologize for this dumb question. i have this simple code:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

now i want to put some series of codes AFTER the user selects "Leave this page".

I know we can use this:

window.onunload = function(){
  alert('bye');
};

but window.onunload only works when the page is refreshed or redirected but not when the browser is closed.

i've also tried this:

window.onbeforeunload = function(){
  if(confirm('are you sure?'))
     alert('exit') //perfectly works
  else
     return false //will display the popup "Stay/Leave" with the message "false" - this is not what i expect
     //preventDefault() -got some error, 
};

what is the best way to add codes AFTER the user clicks "Leave this page"?

OR

is it possible to capture the selection of the user whether STAY or LEAVE?

the whole point is to do something after the user selects any of the options

Eytch
  • 733
  • 3
  • 8
  • 19
  • 1
    Short answer : you can't reliably. – Denys Séguret Jan 02 '14 at 18:46
  • possible duplicate of [How to make a cross-browser on-window-unload request?](http://stackoverflow.com/questions/11317573/how-to-make-a-cross-browser-on-window-unload-request) – Denys Séguret Jan 02 '14 at 18:46
  • thanks for the response @dystroy. i've checked the link you've shared but it's still using the unload event of the window which works fine only when reloading or redirecting the page but not on browser close and to continue reading, it said to NOT depend on beforeunload, whew! wondering if there really aren't any other way – Eytch Jan 02 '14 at 18:50
  • What exactly would you like to happen? – Matt Ball Jan 02 '14 at 18:54
  • The answer is simple : there's no reliable way to do something on browser window close. If the user kindly closes your tab, you may expect to succeed in small operations like changing a local storage, but you can't do any request or display anything apart the standard dialog function. – Denys Séguret Jan 02 '14 at 18:59
  • well let's say when the user closes the browser and clicks "Leave this Page", let's alert('bye') before the browser closed completely (if possible) @MattBall – Eytch Jan 02 '14 at 19:00
  • @dystroy it seems that i really have to agree with you. thanks anyway. this is just disappointing. – Eytch Jan 02 '14 at 19:04
  • anyway please see my updated question. the whole point is to do something after the user selects any of the options – Eytch Jan 02 '14 at 19:05

1 Answers1

4

There is no real reliable way to do this without creating your own browser that would have the capability that you want.

To get started you can look at the Chromium Project

qwertynl
  • 3,912
  • 1
  • 21
  • 43