Setting and Getting Cookies in Javascript

Date Posted: September 2, 2014, 6:17 am


Basic usage:

Set a cookie

1
document.cookie="username=John Doe";

Get a cookie

1
var x = document.cookie;

Function Based:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<script type="text/javascript">
/**
* Set Cookie
*
* @param string cname the name of the cookie
* @param string cvalue value to be set
* @param string cdays number of days before it expires
*
*/

function setCookie(cname, cvalue, cdays) {
    var d = new Date();
    d.setTime(d.getTime() + (cdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

/**
* Set Cookie by path
*
* @param string cname the name of the cookie
* @param string cvalue value to be set
* @param string cdays number of days before it expires
* @param string cpath directory path, ex. "/" to apply to the entire domain
*
*/

function setCookieByPath(cname, cvalue, cdays, cpath) {
    var d = new Date();
    d.setTime(d.getTime() + (cdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires + "; path=" + cpath;
}
/**
* Get Cookie
*
* @param string cname the name of the cookie to retrieve
*
*/

function getCookie(cname) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + cname + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
}
</script>

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me