Trying to run some JS code once a user closes a window/tab

Hello all,

Hoping someone can help me out here… Am looking to write some code that, once the window is closed, it runs some extra JS which loads a *.php file through an AJAX call.

In theory to me it sounds simple but for some reason I cannot get it working. I tried the “onload” attribute but then found that triggers with refresh and links (not good)

I simply need the JS code to start running some other JS when the window closes.

<script type="text/javascript">
	function doUnload() {
		$.post("http://<?php echo $_SERVER['HTTP_HOST']; ?>/includes/logout.php");

Really hope someone can take the time to help out here please.


Once the window is closed there is nothing to run the JavaScript so the JavaScript can’t run then.

Some browsers have a proprietary beforUnload event that allows you to run JavaScript prior to the page being unloaded (for whatever reason - browser closed, tab closed, new page to be loaded, or current page being refreshed). It mostly gets used to place annoying “before you leave” ads and so even in those browsers that do support it many people turn it off.

An alternative option would be to set users which haven’t had activity in the last x minutes as logged out, using a cronjob or altering your query to mean ‘logged in’ as last activity < x minutes go.