Writing Cookies Function

Course- Javascript >

It’s fairly straightforward to write a function to write your cookie for you, leaving all the escaping and the wrangling of optional attributes to the function. The code for such a function appears below.

function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString();
}
else var expires = "";
cookieString = name + "=" + escape (value);
if (expires) cookieString += "; expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString;
}                 
                 

The operation of the function is straightforward. The name and value arguments are assembled into a name=value string, after escaping the value part to avoid errors with any disallowed characters.

Instead of specifying a date string to the function, we are asked to pass the number of days required before expiry. The function then handles the conversion into a suitable date string.

The remaining attributes are all optional and are appended to the string only if they exist as arguments.

Try it Yourself: Writing Cookies

Let’s use this function to set the values of some cookies. The code for our simple page is shown in below code. Create a new file named testcookie.html and enter the code as listed. Feel free to use different values for the name and value pairs that you store in your cookies.

<!DOCTYPE html>
<html>
<head>
<title>Using Cookies</title>
<script>
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
var expires = date.toGMTString();
}
else var expires = "";
cookieString = name + "=" + escape (value);
if (expires) cookieString += "; expires=" + expires;
if (path) cookieString += "; path=" + escape (path);
if (domain) cookieString += "; domain=" + escape (domain);
if (secure) cookieString += "; secure";
document.cookie = cookieString;
}
createCookie("username","Sam Jones", 5);
createCookie("location","USA", 5);
createCookie("status","fullmember", 5);
</script>
</head>
<body>
Check the cookies for this domain using your browser tools.
</body>
</html>                 
                 

Upload this HTML file to an Internet host or a web server on your local area network, if you have one. The loaded page displays nothing but a single line of text:

Check the cookies for this domain using your browser tools.

In the Chromium browser, I can open Developer Tools using Shift+Ctrl+I—if you are using a different browser, check the documentation for how to view cookie information.

displaying our cookies