5

Is there any way to trigger a window/tab close event with jQuery. I already tried with

$('selector').unload() 

But it didn't work.

2
  • version deprecated: 1.8 Commented Jul 24, 2013 at 11:09
  • Please see here for your problem solution. May it will help you. Thank You stackoverflow.com/questions/3888902/… Commented Sep 23, 2016 at 11:48

3 Answers 3

10

You can use unload() on the window property in jQuery:

$(window).unload(function() { //do stuff }); 

You don't need jQuery to do it though, you can use good ol' fashioned JavaScript:

window.onbeforeunload = function(e){ var msg = 'Are you sure?'; e = e || window.event; if(e) e.returnValue = msg; return msg; } 
Sign up to request clarification or add additional context in comments.

2 Comments

java script method worked. thanks but I need something like this $(window).unload(function() { window.location='clearsession.php' }); How can I do it with js
It will also called when user navigate to some other page rather than closing the window
1

In Javascript

window.onbeforeunload = function (event) { var message = 'Important: Please click on \'Save\' button to leave this page.'; if (typeof event == 'undefined') { event = window.event; } if (event) { event.returnValue = message; } return message; }; 

In jQuery

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

1 Comment

It works including page refresh, I need specifically for tab close or browser close
0

Try this

$(window).unload(function() { alert("Unload"); });​ 

Note : some times dialogs are blocked in unload . You can check your console to make it confirm.

1 Comment

What if person is not closing browser but navigating to some other page. unload will also run in that condition.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.