Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Close windows event by jQuery

Could you please give me the best way to detect only window close event for all browsers by jQuery?

I mean clicking X button on the browser or window.close(), not meaning F5, form submission, window.location or link. I was looking for many threads but have not found the right way yet.

like image 836
Duc Le Avatar asked May 23 '13 06:05

Duc Le


People also ask

How do I close a window using jquery?

click(function(){ window. close(); });

How can I tell if my browser window is closed?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

How do you handle a closed event browser?

To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.

How do I know if a popup window is closed?

Here is the code: var win = window. open('http://www.google.com', 'google','width=800,height=600,status=0,toolbar=0'); var timer = setInterval(function() { if(win. closed) { clearInterval(timer); alert('closed'); } }, 1000);


3 Answers

You can use:

$(window).unload(function() {     //do something } 

Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.

The beforeunload event fires whenever the user leaves your page for any reason.

$(window).on("beforeunload", function() {      return confirm("Do you really want to close?");  }) 

Source Browser window close event

like image 153
mjimcua Avatar answered Sep 23 '22 06:09

mjimcua


There is no specific event for capturing browser close event.

You can only capture on unload of the current page.

By this method, it will be effected while refreshing / navigating the current page.

Even calculating of X Y postion of the mouse event doesn't give you good result.

like image 31
Naveenkumar K Avatar answered Sep 23 '22 06:09

Naveenkumar K


The unload() method was deprecated in jQuery version 1.8.

so if you are using versions older than 1.8

then use -

$(window).unload(function(){
alert("Goodbye!");
});

and if you are using 1.8 and higher

then use -

window.onbeforeunload = function() {
    return "Bye now!";
};

hope this will work :-)

like image 39
Rahul Vyas Avatar answered Sep 24 '22 06:09

Rahul Vyas