Header

Tuesday, 2 May 2023

Read cookie using JavaScript Code

Read cookie using JavaScript Code

Today, we'll look at how to use JavaScript code to read cookies. The function readCookie, which is located below, accepts a cookie's name and returns its value.

function readCookie(name) {
  var nameEQ = name + "=";
  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,c.length);
     }
    if (c.indexOf(nameEQ) == 0)
     return c.substring(nameEQ.length,c.length);
    }
  return null;
}

I will demonstrate how to generate cookies using JavaScript in the code below.

function cookieCheck(){
  var interval;
  if(readCookie("userlogTime") == null)
  {
   var cDateTime = new Date();
   var timeSet = cDateTime.getHours();
   document.cookie ="userlogTime="+timeSet;
   }
  }
The above code show how we can create cookie using javascript

No comments:

Post a Comment