First, we define a function that saves the visitor’s name in a cookie.
function setCookie(cname, cvalue, exdays) { const d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); let expires = “expires=”+ d.toUTCString(); document.cookie = cname + “=” + cvalue + “;” + expires + “;path=/”; } |
Explanation of the example:
The function above takes three parameters: the name of the cookie (cname
), the value of the cookie (cvalue
), and the number of days until the cookie should expire (exdays
).
The function creates the cookie by combining the cookie name, cookie value, and the expiration string.
Next, we define a function that retrieves the value of a specified cookie.
function getCookie(cname) { let name = cname + “=”; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(‘;’); for(let i = 0; i <ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ‘ ‘) { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return “”; } |
Explanation of the function:
cname
(cookie name) as a parameter.name
that holds the search text (cname + "="
).document.cookie
is split by semicolons into an array (ca = decodedCookie.split(';')
).ca
array (for (i = 0; i < ca.length; i++)
) and checks each value (c = ca[i]
).c.indexOf(name) == 0
), it returns the cookie’s value (c.substring(name.length, c.length)
).""
).