Search code examples
javascriptcookieserase

Deleting a cookie with value NULL


I'm trying to erase completely a cookie that is set if a particular URL parameter is present.

I've tried:

function delete_cookie (cookie_name) {
    var cookie_date = new Date ();
    cookie_date.setTime(cookie_date.getTime()-1);
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

delete_cookie('MyCookie');

And it sets the cookie value to null but the cookie itself or at least the name of the cookie stays in the browser so that when the same URL is opened again, it will not update the cookie value from null to XXX nor is a second cookie with the URL value created.

For the new cookie to be setup again I have to right-click on the cookie name (in Chrome) and choose delete. This way the cookie name and its value null are truly erased otherwise it stays with null value.

How can I completely erase the cookie file and not just set it to null with javascript?

** NEW INFO **

I should mention that I also have the following function to grab the cookie from the URL parameter and to keep it from the first page until the final page (where it should be deleted after the cookie value is added to another URL). The second page will turn the link into a session where the URL parameter is no longer visible

Here is the code for it:

function URLparam(name) {
return unescape(
    (RegExp(name + '(?:\\[\\d+\\])?=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}

$(document).ready(function () {

if (URLparam("MyParameter") !== null && !get_cookie ("MyCookie")) {
    set_cookie ("MyCookie", URLparam("MyParameter"));
}

Any ideas?


Solution

  • The easiest way to delete the cookie would be like this:

    function delete_cookie( name ) {
        document.cookie = name + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }
    

    Updated: Had to add the path to get it to work.

    Here's a Plunk showing it working. The top buttons in the Plunk use a library to set/view/delete the null cookie. Use the bottom button to delete with the old school method (above) and then use the library show button to verify it is gone.