How to capture the browser window close event?
The beforeunload
event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
For jQuery versions older than 1.7, try this:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
The live
method doesn't work with the submit
event, so if you add a new form, you'll need to bind the handler to it as well.
Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit
and click
events, and checking if the beforeunload
happens more than a couple of seconds later.
How to capture browser tab close event?
You Can try this out..
var new_window = null;
function openWindow(url) {
new_window = window.open(url);
new_window.onbeforeunload = function(){
new_window.opener.postMessage('closed','*');
}
window.onmessage = function(event){
alert(event.data);
}
}
openWindow(url);
How to capture browser close event and make a request to web service method on that event through javascript
You can't.
You can show a standard dialog or do a few fast not interactive operations like writing in localStorage, by using onBeforeUnload, but you can't make a request (in most browsers).
You have to handle the case of browser closing (or network lost, or any incident) server side.
Related Topics
Disabling a Button Within a Stateless Component - React
Error: Permission Denied to Access Property "Document"
Can We Call the Function Written in One JavaScript in Another Js File
Starting the Week on Monday With Isoweekday()
Switch Fontawesome Icon on Click, Not Working
Laravel Reactjs:Changes Are Not Reflecting After Change in My Js(Reactjs) File
Map, and Removing Commas from an Array in JavaScript
Modify Classname When Element Is Clicked in React
How to Add Data Dynamically to Mat-Table Datasource
Get Weeks in Month Through JavaScript
React History.Push() Not Rendering New Component
Enable Utf-8 Encoding for JavaScript
Bootstrap Modal Hide Not Working With Jquery Ajax
Bootstrap Carousel: How to Stop Auto Sliding on Large Screen
Typeerror: Cannot Create Property '_Id' on String
How to Merge the Property With Same Key in Two Object Array