4

Getting and setting Cookies via JavaScript feels a little odd like this:

Set: document.cookie = "<key>=<value>[;expires=<utc_expires>[;path=<path>]]";

Get: parse document.cookie

I found this get and set function on W3C.org Cookies

Is there a more elegant/easy way to do this?

1

2 Answers 2

22

You can use some simple functions like setCookie() and getCookie().

You can set a cookie using the call:

setCookie('myName','value', 3); 

function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }

Note: Source is from quirksmode. Please have a look at the docs if you want to know more about cookies.

Sign up to request clarification or add additional context in comments.

4 Comments

So there is no more elegant way to do this? The getter and setter is essentially the same like to ones I've found on W3C.org
@Pilan: Also Mozilla provides a simple framework for reading and writing cookies- Once included on the page, you can set a cookie using: docCookies.setItem(name, value); This is probably the most elegant way how to achieve this.
Instead of the while loop you can use document.cookie.split(';').map(c => c.trimLeft())
Also instead of if (c.indexOf(nameEQ) == 0) the following executes faster (doesn't search the whole string) and is more descriptive too: if (c.startsWith(nameEQ))
6

ES6 approach is:

const setCookie = (cookieKey, cookieValue, expirationDays) => { let expiryDate = ''; if (expirationDays) { const date = new Date(); date.setTime(`${date.getTime()}${(expirationDays || 30 * 24 * 60 * 60 * 1000)}`); expiryDate = `; expiryDate=" ${date.toUTCString()}`; } document.cookie = `${cookieKey}=${cookieValue || ''}${expiryDate}; path=/`; } const getCookie = (cookieKey) => { let cookieName = `${cookieKey}=`; let cookieArray = document.cookie.split(';'); for (let cookie of cookieArray) { while (cookie.charAt(0) == ' ') { cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(cookieName) == 0) { return cookie.substring(cookieName.length, cookie.length); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.