Member Login:


Remove (delete) a cookie with JavaScript

Document Reference: TN201708003 - Rev: 4.01 - Last Update: 20-08-2017 17:41 GMT - Downloaded: 26-Mar-2019 07:57 GMT

The mcrSf.cookieDel() method requires a minimum of one argument and has an undefined return value.

The required argument defines the cookie name. The optional argument defines the path that the cookie belongs to. The cookie path should be defined to ensure that the right cookie will be deleted. Some browsers will not allow deleting a cookie without specifying the correct path.

Please Note: Due to security issues and other problems, Google Chrome and other popular browsers have disabled storing cookies for local files. Cookies can only be stored and retrieved for files that are served from a webserver.

Parameters

ParameterTypeDescription
cookieNameStringThe name of the cookie.
cookiePath
(Optional)
StringThe path of the cookie.
Optional, default value of '/'.

Return Value

TypeDescription
undefinedThe method has no return value.

The Stand-Alone Function

Below code is ready for copy/paste and will work just fine on it's own, without linking the mcrSf library file.

 function cookieDel(cookieName, cookiePath) {
    var cookieString = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    if (cookiePath !== "") {
        cookiePath = cookiePath || "/";
        cookieString += "; path=" + cookiePath;
    }
    document.cookie = cookieString;
}

The mcrSf Library Method

 /**
* Delete (remove) a cookie
* @version 0.1
* @param {String} cookieName - the name of the cookie
* @param {String} [cookiePath="/"] - the path of the cookie (default: "path=/")
* @return {undefined} - method has no return value
*
* STRATEGY: Set expiry date to 01-01-1970 to the cookie
*/
cookieDel: function(cookieName, cookiePath) {
    var cookieString = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    if (cookiePath !== "") {
        cookiePath = cookiePath || "/";
        cookieString += "; path=" + cookiePath;
    }
    document.cookie = cookieString;
}

Version History

Revision
Date
Details
0.1
05-Aug-17
First release, cookieDel().

This website uses cookies to give you the best experience on our website, to personalise content and to analyse our website traffic. Some cookies may have been set already. To find out more about our use of cookies you can visit our Privacy Statement. By browsing this website, you agree to our use of cookies.

Hide this message