Javascript close browser trap

Supposing you wanted to ensure logged in users logged off (other than checking for some acton serverside)…

this is one solution:



<script type=”text/javascript”>
window.onbeforeunload = function (evt) { logout();  }

function logout() {
var request = new XMLHttpRequest();“POST”, “logout.php”, false);
request.send(‘data={“user”:”<?php echo $user->getId() ?>”}’);


What this does is trap the closing of the tab or window or browser and send an AJAX call out so you can do whatever you need to do.

Of course this won’t stop people from killing the browser via a task manager. But most people just click on the close and unless you use alerts they won’t know that you are performing one extra task as they leave.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s