Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if cookie exists else set cookie to Expire in 10 days

Tags:

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?

like image 620
Learning Avatar asked May 23 '11 02:05

Learning


People also ask

How do you check if a cookie is expired?

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.

How do you set cookies to expire in 30 days?

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.

How do I know if my cookies are set or not?

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.

How we can set cookie expire time?

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.


1 Answers

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"); } 
like image 186
Michael Berkowski Avatar answered Oct 14 '22 10:10

Michael Berkowski