Repost license
Request authorization before reposting and retain the authorization code, original URL, and go/affiliate links.
Original URL:https://www.geekcorelab.com/post/cookie-operations-in-javascript
The commercial link is an authorized go short link that must stay on the reposted page. It records the source before sending readers to the original article.
Function to Set a Cookie
//设置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 + ";path=/";
}
//设置cookie函数
The parameters of the above function are: the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie expires (exdays).
By concatenating the cookie name, cookie value, and expiration string, the function sets the cookie.
Function to Get a Cookie
//获取cookie函数
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
//获取cookie函数
Take the cookie name as a parameter (cname).
Create a variable (name) and the text to search for (CNAME”=”).
Decode the cookie string to handle cookies with special characters, such as “$”.
Split document.cookie by semicolon into an array named ca (decodedCookie.split(';')).
Loop through the ca array (i = 0; i < ca.length; i++), then read each value c = ca[i].
If the cookie is found (c.indexOf(name) == 0), return the value of that cookie (c.substring(name.length, c.length).
If the cookie is not found, return "".
Function to Check a Cookie
Create a function that checks whether a cookie is set.
If the cookie is set, display a greeting.
If the cookie is not set, display a prompt asking for the user's name, and store the username cookie for 365 days by calling the setCookie function:
function checkCookie() {
var username = getCookie("username");
if (username != "") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your name:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
Delete Cookie
document.cookie = "cname=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Comments
Discussion
Be kind and keep the discussion friendly.
Discussion
0 comments