I'm looking for a way to automatically set the user status as "offline" and to do this I need to execute 开发者_StackOverflow中文版a JavaScript function, unless there are any better ideas out there. How can I run a function when the user tries to navigate away from the page? I know there is a way to have a message box appear so there should be a way to do this.
Use the unload
method to call an ajax
method. Note the important async
attribute which says to the browser that it needs to wait the HTTP response before closing the window (to ensure that your server received the "offline" status).
$(window).unload(function() {
$.ajax({
url: "setoffline.php",
async: false
});
});
Try using this one.
<body onbeforeunload="return RunOnClose()">
function HandleOnClose() {
//do your magic here
return true;
}
The follow event fires when the window "unloads":
window.onbeforeunload
I have paired that with an onload event handler in a similar scenario, where I had a row in my DB tracking the user Last Login Session. It had an "entered" date when they login / come to the site and I would set the "Last seen" DateTime on the onunload event, but I was also clearing the "Last seen" date time on the "onload" of the page.
So, the last time they close any page, the "Last Seen" Date is set and it persists
精彩评论