0

Possible Duplicate:
How to execute ajax function onbeforeunload?
How to capture browser close event and make a request to web service method on that event through javascript

So right now this is what my onbeforeunload looks like

window.onbeforeunload = function (e) {
  var message = "Don't close me!",
  e = e || window.event;
  // For IE and Firefox
  if (e) {
    e.returnValue = message;
  }
  // For Safari
  return message;
};

So this is what I'm attempting to do, this function fires and gives them a prompt to choose whether or not to navigate away from the page. If and only if they decide to navigate away I need to fire a GET request to close out the database records.

From testing if I set up like this:

window.onbeforeunload = $.get("url_here")

This was an easy fix however now I can't get the prompt and the window closes without warning.

I've also tried adding a function with a confirm to do it however it doesn't seem to work correctly. E.G.

window.onbeforeunload = function(e){
  if(confirm("Are you sure?")){
    $.get("url_here");

    return true;
  }
}

This one gets weirder, however in most cases it just causes a message to pop up with the literal text ("true") with a yes/no prompt.

Community
  • 1
  • 1
Camway
  • 43
  • 6

1 Answers1

1

have a look at this: http://jsfiddle.net/3kvAC/241 and this Dialog box runs for 1 sec and disappears? and this http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx

it looks like this:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

$(window).unload(function(){
  alert('Bye.');
});
Community
  • 1
  • 1
algorhythm
  • 8,530
  • 3
  • 35
  • 47