Use the event beforeunload with jquery on your page.
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 = false;
$(document).on('click','a', function() { inFormOrLink = true; });
$(document).bind('submit','form', function() { inFormOrLink = true; });
$(window).on('beforeunload',document, function(eventObject) {
var returnValue = undefined;
if (inFormOrLink == false) {
//do your action
}
});
EDIT: Answer found here: How to capture the browser window close event?