0

This Javascript cookie script works great so far, you just adjust when you would like the cookie to expire in the (expiresDays*24) line. However, I would like the cookie to expire when the browser is completely closed, but the cookie to persist whilst you are still on the site, even if you go to another webpage or reload the home page. I read this is doable and can be done with session cookies, by setting the value to 0 or no value, but being a learner on javascript, I am not sure how to do it, do any more experienced programmers know how to adjust the script below to do what I would like?

<script type="text/javascript">
function setCookie(cookieName, cookieValue, expireDays,isGlobal) {
        var expireDate = new Date();
        expireDate.setTime(expireDate.getTime() + 
(expireDays*24*60*60*1000));
        var expires = "expires="+expireDate.toUTCString();
         if(isGlobal){
            document.cookie = cookieName + "=" + cookieValue + "; " + 
expires+"; path=/";
        }else{
            document.cookie = cookieName + "=" + cookieValue + "; " + 
expires;
        }
    }

    function getCookie(cookieName) {
       var name = cookieName + "=";
       var ca = document.cookie.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 "";
 }

function checkCookie(cookieName) {

    if (getCookie(cookieName) != "") {
        return true;
    } else {
        return false;
    }
}
</script>

1 Answers1

1

I fixed this issue, all that was needed was to replace the values in this line:

from (expireDays*24*60*60*1000))

and change to:

(expireDays"=0"))

otherwise I left the scrip unchanged, the cookies lasts the duration of the visit to the website, including if you navigate around the site. But if you completely close the browser, the cookie expires.