Home >Web Front-end >JS Tutorial >How to update cookies in JavaScript? (code example)

How to update cookies in JavaScript? (code example)

藏色散人
藏色散人Original
2019-03-25 11:36:283241browse

Actually, updating a cookie is slightly different than replacing a cookie, because the new value we want to put in the cookie depends somewhat on whether the cookie already exists, and if so, what it contains. This means we need to read the existing cookie before we can write a replacement for it.

How to update cookies in JavaScript? (code example)

One thing to note is that when we read the cookie, we have no way of knowing when the existing cookie expires, or whether the cookie is restricted to a specific folder or in Available throughout the domain. You need to set a new retention period when changing cookies, and you need to track the scope of the cookie within the page so that the same domain or path options apply each time. When you update rather than replace a cookie, the only thing you can actually read is the actual value of the data stored in the cookie.

In this example, we will use a cookie called "accesscount" to count the number of times a visitor visits a page, where each visit is no more than 7 days apart. If the interval between two visits exceeds 7 days, the cookie will expire and the next visit will restart from 0. We used the allCookies() and writeCookie() functions from the previous example, so in order to actually perform the update, we only need the last two lines of code.

Code examples are as follows:

var cookie;
allCookies = function() {
var cr, ck, cv;
cr = []; if (document.cookie != '') {
ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
return cr;
};
writeCookie = function(cname, cvalue, days,opt) {
var dt, expires, option;
if (days) {
dt = new Date();
dt.setTime(dt.getTime()+(days*24*60*60*1000));
expires = "; expires="+dt.toGMTString();
} else expires = '';
if (opt) {
if ('/' = substr(opt,0,1)) option = "; path="+opt;
else option = "; domain="+opt;
} else option = '';
document.cookie = cname+"="+cvalue+expires+option;
}
cookie = allCookies();
if (cookie.accesscount != null) writeCookie('mycookie', cookie.accesscount + 1,7);
else writeCookie('mycookie', 1,7);

Related recommendations: "javascript tutorial"

This article is about updating cookies in JavaScript. Hope it helps those in need!

The above is the detailed content of How to update cookies in JavaScript? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn