User:Mike Dillon/Scripts/cookies.js

From Wikipedia, the free encyclopedia

Note: After saving, you have to bypass your browser's cache to see the changes. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.

/* <pre><nowiki> */
 
function readCookie(name) {
    if (!name) return;
    var nameMatch = name.toLowerCase() + "=";
    var cookies = document.cookie.split(/\s*;\s*/);
    for (var i in cookies) {
        if (cookies[i].toLowerCase().indexOf(nameMatch) == 0) {
            return cookies[i].substr(nameMatch.length);
        }
    }
}
 
function writeCookie(name, value, options) {
    if (value.indexOf(";") != -1) throw "Cookie value cannot contain semi-colons";
 
    if (!options) options = {};
 
    var cookie = name + "=" + value;
    if (options.domain) cookie += ";domain=" + options.domain;
    if (options.path) cookie += ";path=" + options.path;
    if (options.expires || options.expiresInDays > 0) {
        var expires = options.expires;
        if (!expires) {
            expires = new Date(new Date().getTime() + options.expiresInDays * 86400 * 1000);
        }
        if (expires.toGMTString) expires = expires.toGMTString();
        cookie += ";expires=" + expires;
    }
 
    document.cookie = cookie;
 
    return cookie;
}
 
function deleteCookie(name, options) {
    if (!options) options = {};
 
    var epoch = new Date();
    epoch.setTime(0);
    options.expires = epoch;
 
    return writeCookie(name, "", options);
}
 
/* </nowiki></pre> */