JS Set cookie read cookie

  • 2021-01-11 01:51:30
  • OfStack

JavaScript is a script that runs on the client side, so it is usually not possible to set up Session because Session runs on the server side.

cookie runs on the client side, so you can use JS to set up cookie.

js Set cookie to js

1 species:


<script>
// Set up the cookie
function setCookie(cname, cvalue, exdays) {
 var d = new Date();
 d.setTime(d.getTime() + (exdays*24*60*60*1000));
 var expires = "expires="+d.toUTCString();
 document.cookie = cname + "=" + cvalue + "; " + expires;
}
// To obtain cookie
function getCookie(cname) {
 var name = cname + "=";
 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) != -1) return c.substring(name.length, c.length);
 }
 return "";
}
// remove cookie 
function clearCookie(name) { 
 setCookie(name, "", -1); 
} 
function checkCookie() {
 var user = getCookie("username");
 if (user != "") {
  alert("Welcome again " + user);
 } else {
  user = prompt("Please enter your name:", "");
  if (user != "" && user != null) {
   setCookie("username", user, 365);
  }
 }
}
checkCookie(); 
</script>

The second:


<script>
//JS operation cookies methods !

// write cookies
function setCookie(c_name, value, expiredays){
     var exdate=new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
   }
 
// read cookies
function getCookie(name)
{
 var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
 
 if(arr=document.cookie.match(reg))
 
  return (arr[2]);
 else
  return null;
}

// delete cookies
function delCookie(name)
{
 var exp = new Date();
 exp.setTime(exp.getTime() - 1);
 var cval=getCookie(name);
 if(cval!=null)
  document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
// Use the sample 
setCookie('username','Darren',30) 
alert(getCookie("username"));
</script>

Third example


<html> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <head> 
  <script language="JavaScript" type="text/javascript"> 
   
   function addCookie(objName, objValue, objHours){// add cookie 
    var str = objName + "=" + escape(objValue); 
    if (objHours > 0) {// for 0 Do not set an expiration time when the browser is closed cookie Disappear automatically  
     var date = new Date(); 
     var ms = objHours * 3600 * 1000; 
     date.setTime(date.getTime() + ms); 
     str += "; expires=" + date.toGMTString(); 
    } 
    document.cookie = str; 
    alert(" add cookie successful "); 
   } 
   
   function getCookie(objName){// Gets the specified name of the cookie The value of the  
    var arrStr = document.cookie.split("; "); 
    for (var i = 0; i < arrStr.length; i++) { 
     var temp = arrStr[i].split("="); 
     if (temp[0] == objName) 
      return unescape(temp[1]); 
    } 
   } 
   
   function delCookie(name){// To remove the specified name cookie , you can set its expiration time to 1 It's been six years  
    var date = new Date(); 
    date.setTime(date.getTime() - 10000); 
    document.cookie = name + "=a; expires=" + date.toGMTString(); 
   } 
   
   function allCookie(){// Read all saved cookie string  
    var str = document.cookie; 
    if (str == "") { 
     str = " I didn't save anything cookie"; 
    } 
    alert(str); 
   } 
   
   function $(m, n){ 
    return document.forms[m].elements[n].value; 
   } 
   
   function add_(){ 
    var cookie_name = $("myform", "cookie_name"); 
    var cookie_value = $("myform", "cookie_value"); 
    var cookie_expireHours = $("myform", "cookie_expiresHours"); 
    addCookie(cookie_name, cookie_value, cookie_expireHours); 
   } 
   
   function get_(){ 
    var cookie_name = $("myform", "cookie_name"); 
    var cookie_value = getCookie(cookie_name); 
    alert(cookie_value); 
   } 
   
   function del_(){ 
    var cookie_name = $("myform", "cookie_name"); 
    delCookie(cookie_name); 
    alert(" Delete the success "); 
   } 
  </script> 
 </head> 
 <body> 
  <form name="myform"> 
   <div> 
    <label for="cookie_name"> 
      The name of the  
    </label> 
    <input type="text" name="cookie_name" /> 
   </div> 
   <div> 
    <label for="cookie_value"> 
     value  
    </lable> 
    <input type="text" name="cookie_value" /> 
   </div> 
   <div> 
    <label for="cookie_expireHours"> 
     How many hours are expired  
    </lable> 
    <input type="text" name="cookie_expiresHours" /> 
   </div> 
   <div> 
    <input type="button" value=" Add the cookie" onclick="add_()"/><input type="button" value=" Read all cookie" onclick="allCookie()"/><input type="button" value=" Read the name cookie" onclick="get_()"/><input type="button" value=" Delete the name cookie" onclick="del_()"/> 
   </div> 
  </form> 
</body> 
</html>

Note:

chrome Browser cannot get cookie locally. It has to be on the server. If it is local, you can put it under the www directory of local.

Google Chrome only supports read and write operations of cookie on online sites. cookie operations of local html are not allowed. So the following code, if you write it in a local html file, will bring up an empty dialog box.


document.cookie = "Test=cooo";
alert(document.cookie);

If the page is the content of an online site, the content of cookie will normally be displayed Test=cooo, etc.

That's all for this article. I hope you enjoy it.


Related articles: