Entry
onLoad - how do I store each URL in a cookie, then track the number of times it's been loaded
Apr 28th, 2000 08:12
Mike Hall, Chris Tanner,
One simple way is to store a cookie for each page using the URL as the
name and use the value as a counter. First you need some basic functions
for handling cookies:
function setCookie (name, value, expires) {
//Set a cookie given a name, value and expiration date.
document.cookie = name + "=" + escape(value) + "; expires=" +
expires.toGMTString() + "; path=/";
}
function getCookie(name) {
var search;
// Returns the value of the named cookie.
search = name + "=";
offset = document.cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1)
end = document.cookie.length;
return unescape(document.cookie.substring(offset, end));
}
else
return "";
}
function deleteCookie(name) {
var expdate = new Date();
// Delete the named cookie.
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
setCookie(name, "", expdate);
}
Then you can run this code to get and update the counter
var n = window.location; // Get URL for cookie name.
var d = new Date(); // Today's date.
var c; // Holds the counter value.
// Set an expiration date, 30 days in this case.
d.setTime(exp.getTime() + (86400 * 1000 * 30));
// See if the cookie exists already, if not set it to 1. Otherwise
// bump the counter.
if ((c = getCookie(n)) == "")
setCookie(n, 1, d);
else
setCookie(n, c + 1, d);
Note: you don't need to wait for the ONLOAD event to run this.