You can set cookies for domains from which the response originates. For example, a page on www.mydomain.com
can set a cookie for the mydomain.com domain, but not for www.mydomain1.com
. In addition, the HTTP header must be 4kb or less in size.
function setCookie(name, value)
var argvalue = setCookie.arguments.length;
var argc = setCookie.arguments;
var expires = (argc > 2) ? argvalue : null;
var path = (argc > 3) ? argvalue : null;
var domain = (argc > 4) ? argvalue : null;
var secure = (argc > 5) ? argvalue : false;
document.cookie = name + "=" + escape(value) + ((expires==null) ? "" : (";
expires=" + expires.toGMTString())) + (path==null) ? "" : ("; path=" + path)) +
((domain==null) ? "" : ("; domain=" + path)) + ((secure==true) ? "; secure" : "");
The escape() function is used to encode special characters, such as commas, semicolons, and spaces in the value string. The setCookie() function requires the cookie name and value, but you can set the other four arguments, which are optional. The optional arguments should be passed in the proper order. For each argument that is skipped,an empty placeholder should be used. The setCookie() function can be called, as shown:
setCookie("Mycookie1", "Myvalue1", "", "", "", true);
When the client receives a request for a cookie, the cookies.txt file is searched for a match. First, the cookie name is matched. If the name is found and another cookie exists with the same name, the path is matched. After this, the value of the cookie is returned. If the cookie name or the path is not found, the function returns NULL. Following Example shows the function (getCookie() Function) that returns the cookie value when the cookie name is provided.
var arg1 = name + "=";
var arg2 = arg1.length;
var arg3 = document.cookie.length;
var i = 0;
while(i < arg3)
var j = i + arg2;
if (document.cookie.substring(i,j) == arg1)
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
The getCookieVal() function is used to convert the cookies.txt file to bites and extract the correct cookie from it. The getCookieVal() function is as shown below:
You may want to delete a cookie when it is no longer needed. The process to delete a cookie involves setting the cookie value to NULL and setting the expiration date to a past date. Simply setting the expiration to a past date will not delete the cookie because all the values are not reset until the browser is closed. When the browser is open, all cookies are stored in the memory. If you delete cookies by keeping the browser open, the cookies will reappear when you close the browser. Following Example shows the function to delete a cookie.
var exp=new Date();
document.cookie = name + "=" cookieval + ";
expires=" + exp.toGMTString();
If you delete the cookie for a Web site and then revisit the site, the site will recognize you as a first time visitor.