JavaScript Cookies

Cookies are small text files that sit on your hard disk. Cookies are created when you visit a website that uses cookies to store information that they need (or prefer).

Websites often use cookies to personalise the user experience — such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits.

In fact, cookies are so widespread in today's web environment, that it's not often you'll find a website that doesn't use cookies in one way or another. Even if a website doesn't set its own cookies, the site may use an external service that does set cookies (eg, ads, analytics software, etc).

Creating Cookies in JavaScript

Now check your cookies folder to see if the cookie was created. Alternatively, write code to read the cookie.

Note: If the cookie wasn't created, check the expiry date — it needs to be a date in the future.

You can update this value by using the same code with a different value. If you want to add a second value, simply use a different variable name (for example myContents2=).

Reading Cookies in JavaScript

You simply reference the cookie using document.cookie. The only problem with the above code is that it outputs the equals sign and everything before it (eg,myContents=). To stop this from happening, try the following code:

Deleting Cookies in JavaScript

To delete a cookie, you can use the same code you used to create it but this time, set the expiry date in the past:

Once you are comfortable with JavaScript and cookies, you can do things like use the getDate() function to set the date at a date in the future (say, 6 months), creating a function for setting and naming your cookies etc.

Despite the many misconceptions about cookies being malicious, they are usually quite harmless. A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not harder.

However, there are always going to be security implications with any technology that stores data, and cookies are no exception.