0

Is there a way to call a JavaScript when the window closes or the address goes to a completely different site, not just when the page changes? I know I can use onunload, but that seems to trigger when the page changes.

I have an intranet site that I need to keep track of logging in and out. Instead of users always clicking on "Log Out", some of them just close the browser window.

1
  • 1
    I agree that's annoying sometimes, but that's how it is. There's no difference between navigating to another page and closing the current window / tab (navigating to null, in a way) from the script engine's point of view. Commented Jul 27, 2011 at 22:44

3 Answers 3

1

I have an idea. Fire off an AJAX call to some page that "keeps-alive" the current user's session every 30 seconds or so. After a certain time of inactivity (maybe 40 seconds? Make sure it's greater than 30), the server knows the client has become inactive and can log you out. This might seem like overkill, but it's the only way to reliably know when the user is no longer active. Firing off a call when the window is closed might seem like it'd be good, but if the browser crashes or the computer is turned off or something, the call never gets sent anyway.

Sign up to request clarification or add additional context in comments.

Comments

1
window.onbeforeunload = function(){ $.ajax({ url : logoutuser?id=xyz, async : false }); }; 

This will work if when trying to close the window..

One other way is to route all your clicks (for links) on your page through your own custom method -

window.location.href = "someurl"; 

So that way you can sniff where the user tried to navigate to..

Comments

0

For now, unless someone can come up with a better idea, I have the site running in a 100% frame and the onunload script setting on the default page with the frame layout.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.