Zebra Cookie

a ridiculously small (~500 bytes minified) JavaScript API for writing, reading and deleting browser cookies


Download View on GitHub

Zebra Cookie is a ridiculously small (~500 bytes minified, 350 bytes gzipped) JavaScript API for writing, reading and deleting browser cookies



1. Session cookies

A session cookie expires when the browser is closed.

                    // create a session cookie
                    Cookie.write('session_cookie', 'Hello, I am a session cookie. I will expire when the browser is closed');

                    // print cookie values to the console
                    console.log(Cookie.read('session_cookie'));
                    
Run the code and check the browser's console.

2. Expiration time

The expiration time must be set in seconds.
The cookie will expire and be removed from the browser after the set number of seconds pass since the creation of the cookie.

                    // create a cookie that expires in 1 day)
                    Cookie.write('expiring_cookie', 'Hello, I am a cookie that will expire in 86400 seconds (1 day)', 24 * 60 * 60);

                    // print cookie values to the console
                    console.log(Cookie.read('expiring_cookie'));
                    
Run the code and check the browser's console.

3. Reading cookie value

Cookie.read returns null if the read cookie is not set.

                    // read the value of the cookies set in the first 2 examples
                    var session_cookie = Cookie.read('session_cookie');
                    var expiring_cookie = Cookie.read('expiring_cookie');

                    // if the first example has been run
                    if (session_cookie) console.log('Value of cookie from example 1 is: "' + session_cookie + '"');

                    // if the first example has not yet been run
                    else console.log('"session_cookie" does not exist');

                    // if the second example has been run
                    if (expiring_cookie) console.log('Value of cookie from example 2 is: "' + expiring_cookie + '"');

                    // if the second example has not yet been run
                    else console.log('"expiring_cookie" does not exist');
                    
Run the code and check the browser's console.

4. Deleting cookies

                    // delete cookie from the first example
                    Cookie.destroy('session_cookie');

                    // print cookie value to the console (should be "null")
                    console.log(Cookie.read('session_cookie'));

                    // delete cookie from the second example
                    Cookie.destroy('expiring_cookie');

                    // print cookie value to the console (should be "null")
                    console.log(Cookie.read('session_cookie'));
                    
Run the code and check the browser's console.

copyright © 2011 - stefan gabos