Questions about this topic? Sign up to ask in the talk tab.

Cookies/Setting A Cookie/Javascript (Client Side)

From NetSec
Jump to: navigation, search

To set a cookie, you need to set a properly formatted string to the document.cookie string. Automagically, your browser will add the cookie in the site's jar. You may add all the parameters we describe in here

In order to get the properly formatted string, best option is to use a Date object, which has a very practical toGMTString() method. See this sample

<syntaxhighlight lang="javascript"> // set a cookie that will expire in 30 minutes (1800 seconds), // limited to domains under .staff.blackhatacademy.org // to be transmitted over HTTP // or HTTPS, it doesn't matter to us. var d = new Date(); var expires = new Date(d.getTime()+1800).toGMTString(); document.cookie = "my_lover="+encodeURIComponent("hero hitler in love, or was it Mr #?")+";Expires="+expires+";Domain=.staff.blackhatacademy.org"; </syntaxhighlight>

Feel free to expand this example, put it in a nicely wrapped function, to parameterize it, and whatnot.