Skip to content
Sign upLog in
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
4

JavaScript Cookie Functions: 1.0

josef24
josef24

To add the cookie functions, first create cookies.js and copy paste this code:

function addCookie(name, value, days) { var dt = new Date; dt.setTime(dt.getTime() + (days*24*60*60*1000)); var expires = "expires="+ dt.toUTCString(); document.cookie = name + "=" + value + ";" + expires + ";path=/"; console.log("Sucessfully created cookie " + name); } function getCookie(name) { var cname = name + "="; 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 ""; } function checkCookie(name) { var username = getCookie(name); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { addCookie(name, "user", 365); } } } function deleteCookie(name) { var expires = -1 var dt = new Date; dt.setTime(dt.getTime() + (expires*24*60*60*1000)); var expires = "expires="+ dt.toUTCString(); document.cookie = name + "=" + 0 + ";" + expires + ";path=/"; console.log("Sucessfully deleted cookie " + name); } function changeAndRenewCookie(name, value, expires) { addCookie(name, value, expires) }

Then in html copy paste this:

<script src="cookies.js"></script>

You are free to modify the code, but if you post the modifed code, link to this post.
The repl below will explain:

3 years ago

Voters

Comments

TopNew
1
RealAwesomeSam
RealAwesomeSam

ReferenceError: setCookie is not defined
at checkCookie (/cookies.js:30:8)
at /script.js:4:1

7 months ago
1
DynamicSquid
DynamicSquid

I'm confused, what does this do?

3 years ago
1
josef24
josef24

@DynamicSquid

It enables you to create, delete, and check cookies.

3 years ago
3
DynamicSquid
DynamicSquid

@josef24
ooooooooh, web cookies. I though you were talking about actual cookies lol

3 years ago
Load more