On a project I'm currently working on, I needed to record a users last access time when they left the website, either by logging out, closing the browser, or visiting another website. You want to use the
onbeforeunload event. I had this run a javascript function to make a synchronous (ajax) call to a PHP script which did the work. Using the onbeforeunload event will do what you want.
My code, if it helps:
-
// add event listener
-
function addListener(obj, event, func) {
-
var obj = (typeof obj == 'string' ? d.getElementById(obj) : obj);
-
if (obj && obj.addEventListener) {
-
obj.addEventListener(event, func, false);
-
} else if (obj && obj.attachEvent) {
-
obj.attachEvent('on'+event, func);
-
}
-
}
-
-
// return AJAX object
-
function getHttpXml() {
-
if (window.XMLHttpRequest) {
-
return new XMLHttpRequest();
-
} else if (window.ActiveXObject) {
-
try {
-
return new ActiveXObject("Msxml2.XMLHTTP");
-
} catch (e) {
-
try {
-
return new ActiveXObject("Microsoft.XMLHTTP");
-
} catch (e2) { } // no Ajax support
-
}
-
} return null;
-
}
-
-
addListener(window, 'beforeunload', bye);
-
var xmlHttp = getHttpXml();
-
-
function bye() {
-
if (xmlHttp) {
-
var url = "script.php?action=leaving";
-
xmlHttp.open("GET", url, true);
-
xmlHttp.send(null);
-
}
-
}
-
-
-
You can add this in the head of your html page, if you want, just edit the relevant line to change the filename / parameters you want to call. I hope that helps.