Jump to content

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. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* <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> */