Nikolay
Nikolay

Reputation: 165

Javascript alert when user closes the tab ot the window

I want when a user closes the tab or window or when he tries to move to another location different from my site to pops a confirm box, and if he confirm to execute an ajax script and then to close or change the window. I don't know how to do that. PS: I'm using jQuery.

Upvotes: 2

Views: 8711

Answers (2)

Marty
Marty

Reputation: 43

<script language="JavaScript">
  function unload() {
      alert('window closed');
  }
window.onunload = unload;
</script>

Upvotes: 3

Matthew Riches
Matthew Riches

Reputation: 2286

$(window).unload(function() {
    var answer=confirm("Are you sure you want to leave?");
if(answer){
    //ajax call here
    }
});

Just add your own alert/dialogue code to the function.

Upvotes: 5

Related Questions