I'm working on realtime AJAX application with long polling in NodeJS. I would like to detect when user closes the tab with pending long-polling request. I use NodeJS connection close event:
request.connection.on('close', function () {
console.log(request.url);
...
});
The AJAX loop looks like this:
var EventLoop = new (function () {
var self = this;
this.listen = function () {
$.postJSON(
'recieve-events',
{ /* some data not important for this issue */ },
function (data) {
...
self.listen();
}
);
}
})();
This is how the postJSON function is defined:
$.extend({
postJSON: function (url, data, callback) {
$.ajax({
'url': url,
'dataType': 'json',
'data': data,
'type': 'POST',
'success': callback
});
}
});
The problem is, that the connection close event is fired twice, when I close the tab. Can anyone explain me why and how to prevent this behaviour?
I know, that I can use counter and call the callback function just first time, but I don't consider this as a nice solution, since it doesn't make logical sense to me to close something, that is already closed. (firing the event twice)