Javascript manipulating multiple cookie values in one cookie
Sometimes,its convenient to store values in cookies and retrieve it later.But,when dealing with different browsers,you may have problems as different browser may support different numbers of cookies.For example, IE can only support up to 20 cookies for one single domain. Therefore, we may need to compact our cookies into one instead of more.
How do we do that in Javascript?
Lets say originally we have like 3 cookies value storing for the same domain.
document.cookie = "cookie1=val1;path=/;domain=just-thor.com" document.cookie = "cookie2=val2;path=/;domain=just-thor.com" document.cookie = "cookie3=val3;path=/;domain=just-thor.com"
By using javascript, first of all we store all 3 values into 1,and separate it by a separator.
document.cookie = "allcookies=cookie1=val1|cookie2=val2|cookie3=val3;path=/;domain=just-thor.com"
Instead directly reading from cookies,first we translate our cookies value into array.
var cookieArray = translateCookiesToArray(new Array(), "allcookies");
// you can append more items into the array by calling
// cookieArray = translateCookiesToArray(cookieArray, "anotherCookiesCollection");
function translateCookiesToArray(result, key) {
rawString = getCookieValue(key);
if (rawString != null) {
tokenizedString = rawString.split("|");
for (i=0;i<tokenizedString.length;i++){
innerArray = tokenizedString[i].split("=");
result[innerArray[0]] = innerArray[1];
}
}
return result;
}To get value for cookie1,simply type
cookieArray["cookie1"]
You can always refactor it by globalize the separator variable and the way you access cookieArray. Refer to the code below.
Here’s the complete code
var cookieArray = translateCookiesToArray(new Array(), "allcookies");
function translateCookiesToArray(result, key) {
rawString = getRawCookieValue(key);
if (rawString != null) {
tokenizedString = rawString.split("|");
for (i=0;i<tokenizedString.length;i++){
innerArray = tokenizedString[i].split("=");
result[innerArray[0]] = innerArray[1];
}
}
return result;
}
function getRawCookieValue(name)
{
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieByOffset(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieByOffset (offset)
{
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
function getCookieValue (name)
{
value = cookieArray[name];
if (typeof value == "undefined") {
value = null;
}
return value;
}
//retrieving value
var val1 = getCookieValue("cookie1");Feel free to leave any comment.
Happy coding












Recent Comments