Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if a cookie is already there?

So I do simple JS function like

function writeCookie() 
{ 

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height; 

document.cookie=the_cookie 

} 

how tm make sure that users_resolution is set?

like image 342
Rella Avatar asked Feb 26 '23 17:02

Rella


1 Answers

You could write a function like so:

  function getCookie(cName) {
    var cVal = document.cookie.match('(?:^|;) ?' + cName + '=([^;]*)(?:;|$)');
    if (!cVal) {
      return "";
    } else {
      return cVal[1];
    }
  }

Then, after you have set the cookie, you can call getCookie() and test it's return value, if it's equal to an empty string, or "", which is false, then the cookie doesn't exist. Otherwise you've got a valid cookie value.

The above paragraph in code:

var cookie = getCookie("users_resolution");
if (!cookie) {
   // cookie doesn't exist
} else {
  // cookie exists
}
like image 87
Alex Avatar answered Mar 12 '23 12:03

Alex