0

Possible Duplicate:
Capturing result of window.onbeforeunload confirmation dialog

I want to make user confirm page navigation like that:

window.onbeforeunload = function(e) {
    return "Note that any unsaved data will be lost";
};

however, I want to detect if user clicked "Stay in this page" to do something important. So is there anyway to detect which button is clicked?

NB: I tried adding confirm in the onbeforeunload function but chrome block it.

Community
  • 1
  • 1
Samer El Gendy
  • 1,683
  • 2
  • 23
  • 45
  • A confirm is'nt needed as the onbeforeunload function will trigger it's own confirm when a string is returned and it will either leave the page or not, depending on what the user selected, so that should'nt really be an issue ? – adeneo Sep 09 '12 at 21:35
  • Can you set up a jsfiddle with some code? – elclanrs Sep 09 '12 at 21:35

2 Answers2

1

There is no way to execute code right after the user decided to stay on the page.

You can use the onunload event to do something in case the user does not stay. If you want to send an AJAX request that's one of the few cases where async: false is appropriate.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Actually, just calling a function inside a small timeout right above the return statement would delay the execution of that function until the confirm was answered, and the function would of course only execute if the user decided to stay -> [FIDDLE](http://jsfiddle.net/HNnN6/1/)... – adeneo Sep 09 '12 at 21:57
  • @adeneo This seems to work with chrome, but not FF. – Ashley Strout Sep 09 '12 at 22:03
  • @D.Strout - did'nt really test it, just an idea, but it seems to work for me in FF, but clearing the timeout in the unload function would probably be a better idea, it was just to make a point really that a function can be set to run if the user decides to stay on the page, but as far as I'm concerned this is the right answer. – adeneo Sep 09 '12 at 22:10
  • That timeout might also trigger in case the user waits too long and then does not stay on the page. – ThiefMaster Sep 09 '12 at 22:11
  • The timeout is delayed while the confirm is visible. – adeneo Sep 09 '12 at 22:11
0

Try like this

$(document).ready(function(){
    $('body').live('click',function(){
       $clicked = (this).attr("value");
       alert($clicked);
  });  
})

Consider that your buttons value should be your message like:"Note that any unsaved data will be lost"

GautamD31
  • 28,552
  • 10
  • 64
  • 85