Home > Article > Web Front-end > How to operate cookies using pure JS
This time I will show you how to operate pure JS operations Cookie, what are the precautions for operating pure JS cookies , the following is a practical case, let's take a look.
A cookie is a variable that is stored on the visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values.
Add Cookie
Description:
Create a new cookie and let it be managed by the browser!
Parameter description:
name - key The key of the value pair, uniquely marks a value
value - the value of the key-value pair, the content stored in the cookie
expdays - cookie expiration time (valid time)
function setCookie ( name, value, expdays ){ var expdate = new Date(); //设置Cookie过期日期 expdate.setDate(expdate.getDate() + expdays) ; //添加Cookie document.cookie = name + "=" + escape(value) + ";expires=" + expdate.toUTCString(); }
Get Cookie
Description:
According to the parameter name, get the corresponding value in the cookie
function getCookie ( name ){ //获取name在Cookie中起止位置 var start = document.cookie.indexOf(name+"=") ; if ( start != -1 ) { start = start + name.length + 1 ; //获取value的终止位置 var end = document.cookie.indexOf(";", start) ; if ( end == -1 ) end = document.cookie.length ; //截获cookie的value值,并返回 return unescape(document.cookie.substring(start,end)) ; } return "" ; }
Delete Cookie
Description:
According to name, delete a cookie (set to expire immediately)
function delCookie ( name ){ setCookie ( name, "", -1 ) ; }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Related reading:
What should I do if the browser is not compatible with the code I wrote
Summary of commonly used array methods in JS
Detailed graphic explanation of Vue.js
The above is the detailed content of How to operate cookies using pure JS. For more information, please follow other related articles on the PHP Chinese website!