Javascript set cookie(read, modify and delete)

Lionsure 2020-06-22 Original by the website

In the process of website development, using javascript to set cookies is not only often used, but also can reduce the burden on the server, and sometimes it is necessary. For example, the menu on the left side of the background management system is to use javascript to operate cookies.

Javascript operation cookies include setting, reading, modifying and deleting, they have no existing methods, you need to write your own code and encapsulate it into a method; For convenience, they have been shared below.

 

1. Javascript set cookie

function setCookie(cookieName, cookieValue, expireHours){

       var CookieStr = cookieName + "=" + escape(cookieValue);

       //Without setting the expiration time, the cookie disappears automatically when the browser is closed
              if(expireHours > 0){

              var date = new Date();
                     var ms = expireHours * 3600 * 1000;

              date.setTime(date.getTime() + ms);
                     str += "; expires=" + date.toGMTString();
              }
              document.cookie = CookieStr;
       }

Call: setCookie("myCookie","menu1",2);

 

2. Javascript read cookie(i.e. Javascript get cookie)

function getCookie(cookieName){

       var cookieStr = document.cookie.split(";");

       for (var i = 0; i < cookieStr.length; i++){

              var val = cookieStr[i].split("=");

              if (escape(cookieName) == val[0])
                     return unescape(val[1]);
              }
              return null;
       }

Call: getCookie("myCookie");

 

3. Javascript delete cookie

function DeleteCookie(CookName){

       var date = new Date();
              date.setTime(date.getTime() - 10000);

       var val = getCookie(cookieName);
              if(val != null)
                     document.cookie= cookieName + "=;expires=" + date.toGMTString();
       }

Call: DeleteCookie("myCookie");