js uses cookie to remember user page operation

  • 2021-11-01 23:06:33
  • OfStack

Preface

In the development process, we sometimes encounter a similar requirement, such as remembering what users do at the browser level. I have done a function before. At that time, I used a drag-and-drop plug-in to display a report diagram similar to 9 squares, and each diagram can be displayed and hidden. If the user clicks the Show or Hide button, the browser will keep the last operation result when entering the system next time. The core part is to use js to operate cookie, while the specific business part is to delete div corresponding to the graphic from cookie if it is hidden when triggering the graphic click event, and write the graphic div into cookie when clicking display. This article only records cookie part of the operation, the specific business code we can write according to their actual situation.

When is cookie?

cookie has the size of 4kb, and if it exceeds the length, it will return an empty string; cookie is stored in the client, which can be easily modified and viewed, so cookie cannot be used to store important information; The life cycle of cooki will end after the browser is closed. If you want to use it within 1 event, we can set the effective time for cookie;

Cookie, sometimes in its plural form Cookies, refers to the data (usually encrypted) stored on the user's local terminal by some websites for session tracking to identify the user. Definitions in RFC 2109 and 2965 have been discarded, and the latest replacement specification is RFC 6265 [1]. (Can be called a browser cache)
-Quoted from Baidu Encyclopedia

The method is as follows

1. Set cookie parameters: cname: cookie name, cvalue: cookie value, exdays: cookie expiration time


function setCookie(cname,cvalue,exdays)
{
 var d = new Date();
 d.setTime(d.getTime()+(exdays*24*60*60*1000));
 var expires = "expires="+d.toGMTString();
 document.cookie = cname + "=" + cvalue + "; " + expires;
}

2. Get cookie


function getCookie(cname)
{
 var name = cname + "=";
 var ca = document.cookie.split(';');
 for(var i=0; i<ca.length; i++) 
 {
 var c = ca[i].trim();
 if (c.indexOf(name)==0) return c.substring(name.length,c.length);
 }
 return "";
}

3. Delete cookie


function delCookie(cname)
{
 var exp = new Date(); 
 exp.setTime(exp.getTime()-1); 
 var cval = getCookie(cname);
 if(cval != null){
	document.cookie = cname + "=" + cval + ";expires=" + exp.toGMTString();
 }
}

I hope this article is helpful to you. If it is useful, remember to pay attention to me and continue to output more content for everyone in the later period

Reference: cookie operation

Summarize


Related articles: