Here is what I'm looking to do (pseudo-code):
Imagine the name of the cookie in the example is "visited" and it contains nothing.
if visited exists then alert("hello again"); else create visited - should expire in 10 days; alert("This is your first time!")
How can I achieve this in JavaScript?
Right-click anywhere on a web page, on the website where you want to check the cookie expiration date. Then, open up the developer tools by selecting Inspect or Inspect element, depending on the browser.
time()+60*60*24*30 will set the cookie to expire in 30 days. If not set, the cookie will expire at the end of the session (when the browser closes). The path on the server in which the cookie will be available on.
Right-click and click on Inspect Element to open the developer console. Go to the Storage tab. Expand the Cookies menu and select the website to check cookies. On the right side of the console, you will see the cookies that have been set on the website.
You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the 'expires' attribute to a date and time.
You need to read and write document.cookie
if (document.cookie.indexOf("visited=") >= 0) { // They've been here before. alert("hello again"); } else { // set a new cookie expiry = new Date(); expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes // Date()'s toGMTSting() method will format the date correctly for a cookie document.cookie = "visited=yes; expires=" + expiry.toGMTString(); alert("this is your first time"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With