JavaScript when the window closes?
Is there a way to call a JavaScript when the window closes or the address goes to a completely 开发者_StackOverflowdifferent 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.
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.
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..
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.
精彩评论