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.
click(function(){ window. close(); });
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.
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.
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);
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
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.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With