简体   繁体   中英

Javascript - Check if cookie exists

I have trying to see if a cookie exists or not, Here is my getCookie method:

function getCookie(name)
    {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    }

and here is how I calling that method:

var cookie = getCookie("counter");

and here is my condition I tried:

if(cookie == '')
        {
        }
        else
        {
             //Always goes here even when I clear my cookies and I know it does not exist.
        }

My condition always goes into the else, not matter what, what am I doing wrong?

You can check the value of cookie if not undefined

    if (typeof(cookie)  === 'undefined'){
     CONSOLE.LOG('no cookie');
    } else {
     CONSOLE.LOG(' cookie exist');
    }

Please try following function to get cookie:

    function getCookie(c_name){
    var c_value = document.cookie;
    var c_start = c_value.indexOf(" " + c_name + "=");
    if (c_start == -1){
      c_start = c_value.indexOf(c_name + "=");
    }
    if (c_start == -1){
      c_value = null;
    }
    else {
      c_start = c_value.indexOf("=", c_start) + 1;
      var c_end = c_value.indexOf(";", c_start);
      if (c_end == -1)
      {
    c_end = c_value.length;
    }
    c_value = unescape(c_value.substring(c_start,c_end));
    }
    return c_value;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM