how can i test my script to delete cookies

ma p Source

I wrote a script in javascript to delete all cookies (except some included in a whitelist) within the current domain (using document.cookie). How can I make sure that it is working and indeed deleting the cookies?

I ran it in the browser by including it in an html file and then opening that file, but I don't understand how to test that it will delete cookies within the domain since when I open an html file it is not associated with a domain.

Here is my code:

//cookies we need
  const whitelist = [
  'example_cookie', 
  ]; 


function removeUnnecessaryCookies() {
  let decodedCookie = decodeURIComponent(document.cookie);   //check for special characters 
  let allCookies = decodedCookie.split(';'); //make array of all cookies in domain 

  for (var i = 0; i < allCookies.length; i++) {
    let cookie = allCookies[i];
    if (!whitelist.includes(cookie)) {
      deleteCookie(cookie); 
    }
  }
}

/* helper function to delete cookies */
function setCookie(cookieName, cookieValue, cookieExpiry) {
  let date = new Date();
  date.setTime(date.getTime() + (cookieExpiry*24*60*60*1000));
  let expires = "expires=" + date.toUTCString();
  document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}

function deleteCookie(cookieName) {
  setCookie(cookieName, '', -100);
}

removeUnnecessaryCookies();
javascripttestingcookiessetcookiejs-cookie

Answers

answered 4 months ago Simon Franzen #1

Write a getCookie method and test for that. Here is an example:

function setCookie(name, value, days) {
    var expiry = new Date()
    expiry.setTime(expiry.getTime() + (days * 24 * 60 * 60 * 1000))
    var expires = 'expires=' + expiry.toUTCString()
    document.cookie = name + '=' + value + ';' + expires + ';' + 'path=/'
}

function getCookie(name) {
    var name = name + '='
    var decodedCookie = decodeURIComponent(document.cookie)
    var ca = decodedCookie.split(';')

    for(var i = 0; i < ca.length; i++) {
        var c = ca[i]

        while (c.charAt(0) == ' ') {
            c = c.substring(1)
        }

        if (c.indexOf(name) == 0) return c.substring(name.length, c.length)
    }

    return false
}


// set cookie
setCookie('mycookie', '1', 365);

// get cookie
getCookie('mycookie');
getCookie('joe'); // returns false

answered 4 months ago Tony D #2

Your best bet would be to spin up a localhost webserver (something like WAMP or MAMP or Mac should do the trick) and drop a cookie. Look at the domain in your browser and copy that.

comments powered by Disqus