You can bind to the unload event:
function SomeObject(){ ... var that = this; $(window).unload(function() { that.destroy(); }); }
Thus, your destroy method will be called when the user leaves the page.
Without jQuery, you can associate an event with this:
var event = 'load'; var handler = function() { ... }; if (window.addEventListener) { window.addEventListener(event, handler, false); } else { window.attachEvent('on'+event, handler); }
source share