Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a cookie exists?

What's a good way to check if a cookie exist?

Conditions:

Cookie exists if

cookie1=;cookie1=345534; //or cookie1=345534;cookie1=; //or cookie1=345534; 

Cookie doesn't exist if

cookie=; //or <blank> 
like image 572
confuzzled Avatar asked May 11 '11 17:05

confuzzled


People also ask

How do you check if a cookie exists or not?

document. cookie. indexOf('cookie_name='); It will return -1 if that cookie does not exist.

How do I know if my cookies are expired?

Right-click anywhere on a web page, on the website where you want to check the cookie expiration date. Then, open up the developer tools by selecting Inspect or Inspect element, depending on the browser.

How do I delete document cookies?

Delete a Cookie with JavaScript Just set the expires parameter to a past date: document. cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.


2 Answers

You can call the function getCookie with the name of the cookie you want, then check to see if it is = null.

function getCookie(name) {     var dc = document.cookie;     var prefix = name + "=";     var begin = dc.indexOf("; " + prefix);     if (begin == -1) {         begin = dc.indexOf(prefix);         if (begin != 0) return null;     }     else     {         begin += 2;         var end = document.cookie.indexOf(";", begin);         if (end == -1) {         end = dc.length;         }     }     // because unescape has been deprecated, replaced with decodeURI     //return unescape(dc.substring(begin + prefix.length, end));     return decodeURI(dc.substring(begin + prefix.length, end)); }   function doSomething() {     var myCookie = getCookie("MyCookie");      if (myCookie == null) {         // do cookie doesn't exist stuff;     }     else {         // do cookie exists stuff     } } 
like image 82
jac Avatar answered Sep 17 '22 10:09

jac


I have crafted an alternative non-jQuery version:

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/) 

It only tests for cookie existence. A more complicated version can also return cookie value:

value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1] 

Put your cookie name in in place of MyCookie.

like image 35
hegemon Avatar answered Sep 19 '22 10:09

hegemon