极
极核实验室

JavaScript Cookie Operations

AI summary
该文章介绍了如何使用JavaScript设置、获取、检测和删除cookie。setCookie函数通过指定cookie名、值和过期天数来设置cookie。getCookie函数通过cookie名获取其值,并处理特殊字符。checkCookie函数检测cookie是否存在,若存在则显示问候,否则提示用户输入名字并设置cookie。删除cookie通过将过期时间设置为1970年1月1日实现。文章提供了相关函数的实现代码和逻辑说明。

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.

Complete your profile details to improve the chance of approval.

Your email will not be shown publicly.

Loading...

Markdown supported.

Discussion

0 comments

Internal link graph

Loading internal links…

View linked articles