How to Capture the Browser Window Close Event

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



Leave a reply



Submit