Saving an array to cookies in javascript - javascript

I am trying to save an array in cookies:
setCookie("a", JSON.stringify([{a:1},{a:2}]))
But seems that browser stores a decoded version of my string and when I try to retrieve it:
JSON.parse(getCookie("a"))
I get parsing error. What is the solution to solve this problem?

Here is how to create/get a cookie with array value in javascript
JSON encode it, effectively producing a string like "{name:'myname',age:'myage'}" which you put in a cookie, retrieve when needed and decode back into a JavaScript array/object.
Example - store array in a cookie:
var arr = ['foo', 'bar', 'baz'];
var json_str = JSON.stringify(arr);
createCookie('mycookie', json_str);
Later on, to retrieve the cookie's contents as an array:
var json_str = getCookie('mycookie');
var arr = JSON.parse(json_str);
Note: cookie functions are not native, taken from How do I create and read a value from cookie? , see below:
var createCookie = function(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

Try to use createCookie and getCookie. It gives you a parser error because getCookie("a") returns undefined.

try to serialize the JSON data into single String and saving it in the cookie while read it back unserialize the String and convert it back to JSON string or JSON object

Related

Convert a date in GTM String format to a date object in Javascript

From Java I need to set a cookie expiry time to cookie content instead of setting a expiry time to this cookie. Following code shows how this was done.
public static Cookie addOPBrowserStateCookie(HttpServletResponse response) {
int expiresSeconds = 120;
Date date = new Date();
date = new Date(date.getTime() +1000 * expiresSeconds);
String expiryTime = date.toGMTString();
Cookie cookie =
new Cookie(OIDCSessionConstants.OPBS_COOKIE_ID, UUID.randomUUID().toString() + "_" + expiryTime);
cookie.setSecure(true);
cookie.setPath("/");
response.addCookie(cookie);
return cookie;
}
Then from Javascript I need to convert this String back to a date object and compare with the current date value. Following is the way I tried to do that.
function getOPBrowserState() {
var name = "opbs=";
var cookie = document.cookie + ";";
var start = cookie.indexOf(name);
if (start != -1) {
var end = cookie.indexOf(";", start);
opbs = cookie.substring(start + name.length, end);
}
console.log(opbs);
var c = opbs.split('_');
var result = c[0];
var expiry_time = Date.parse(c[1]);
var now = Date.now();
console.log(expiry_time.toString());
if (expiry_time < now) {
return null;
}
else {
return result;
}
}
However when I use Date.parse on the String I keep getting Nan value for the expire_date. Appreciate your help on this.
Thanks!

Is it possible to delete a cookies using its VALUE NOT NAME using JavaScript? If yes, then how?

function addit(x, y, z) {
c = document.getElementById("count");
iname = document.getElementById("itemname");
pic = document.getElementById(z).src;
n = parseInt(c.value);
n += 1;
document.cookie = "itemname" + n + "=" + x;
document.cookie = "itemprice" + n + "=" + y;
document.cookie = "itemimgsrc" + n + "=" + pic;
c.value = n;
}
I am creating cookies with the above function successfully and now need a function to delete these cookies but NOT with the NAME of the cookies but using their VALUE. The one who have down voted my question, read the question again please, everywhere people have explained to delete a cookie using its NAME but I need to do it using its VALUE, NOT NAME, Thanks.
You can do it like this:
document.cookie = "itemname" + n + "=''";
Or like this:
document.cookie = "itemname" + n + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT;";
Just give it no value and a previous date

javascript set cookie IE7

I have this function for setting cookies, it works GREAT on all browsers,
but it in ie7 it simply doesn't save the cookie.
Any ideas why?
(the input to the function is valid, I tripled checked it)
function SetCookie(cookieName, cookieValue, nDays) {
try {
var today = new Date();
var expire = new Date();
if (nDays == null || nDays == 0) nDays = 1;
expire.setTime(today.getTime() + 3600000 * 24 * nDays);
var newCookie = cookieName + '=' + cookieValue + '; expires=' + expire.toGMTString()+'; path=/';
document.cookie = newCookie;
} catch (e) {
showAlert('SetCookie:' + e.message);
}
}
I found the answer and it happened only on ie 7, 8.
I have several sub domains on my dev and qa environment
like: dev.site.com qa.site.com developerName.site.com
and of course site.com
I noticed that if you log in to any sub domain the cookie is ok,
but when you go to regular domain it messes up the sub domains cookies.

Set a cookie expire after 2 hours

I have this JavaScript code:
function spu_createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
How can I make the cookie expire after 2 hours?
If you want to use the same type of function, transform the days param into hours and pass 2 to get a 2 hour expiration date.
function spu_createCookie(name, value, hours)
{
if (hours)
{
var date = new Date();
date.setTime(date.getTime()+(hours*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
{
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that:
Adding hours to Javascript Date object?
Try this:
function writeCookie (key, value, hours) {
var date = new Date();
// Get milliseconds at current time plus number of hours*60 minutes*60 seconds* 1000 milliseconds
date.setTime(+ date + (hours * 3600000)); //60 * 60 * 1000
window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
return value;
};
Usage:
<script>
writeCookie ("myCookie", "12345", 24);
</script>
//for 24 hours
Try jquery-cookie. Makes it very easy to work with cookies.
The following one-liner will set a cookie, name, with the value, value, and an expiration of two hours from the time of its creation. If the optional argument, days, is supplied, the cookie will expire after that many days instead.
Warning: there is no error-checking, so if mandatory parameters are omitted when called, or arguments are mistyped, the function will throw an error.
spu_createCookie = (name, value, days) => { document.cookie = `${name}=${value}; expires=${new Date(Date.now() + (days ? 86400000 * days : 7200000)).toGMTString()}; path=/` }
Relevant JavaScript syntax concepts:
Arrow Functions
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Template Literals
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Ternary Operators
The conditional (ternary) operator is the only JavaScript operator that takes three operands ... This operator is frequently used as a shortcut for the if statement.
This would do it.
var now = new Date();
var time = now.getTime();
time += 7200 * 1000;
now.setTime(time);
document.cookie =
name+ '=' + value +
'; expires=' + now.toGMTString() +
'; path=/';

How can I delete all cookies with JavaScript? [duplicate]

This question already has answers here:
Clearing all cookies with JavaScript
(26 answers)
Closed 6 years ago.
I have written code to save cookies in JavaScript. Now I need to clear the cookies irrespective of values that I assigned.
Are there any script modules to delete all cookies that were generated by Javascript?
My Sample Code:
document.cookie = 'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
How else could I clear all of the cookies?
Will there will be any problems when I test the code on the webserver?
There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".
Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!
However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:
function clearCookie(name, domain, path){
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
On the face of it, it looks okay - if you call eraseCookie() on each cookie that is read from document.cookie, then all of your cookies will be gone.
Try this:
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
eraseCookie(cookies[i].split("=")[0]);
All of this with the following caveat:
JavaScript cannot remove cookies that have the HttpOnly flag set.
This is a function we are using in our application and it is working fine.
delete cookie: No argument method
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
Edit: This will delete the cookie by setting it to yesterday's date.
Why do you use new Date instead of a static UTC string?
function clearListCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++){
var spcook = cookies[i].split("=");
document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";
}
}

Categories

Resources