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;";
}
}
Related
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
I have a chrome extension where i store a cookie within the document.cookie. This is then refetched every time the user opens the popover.
I have used the Microsoft Edge convertor tool, to convert the extension to support the edge browser. This all worked as expected.
However a cookie is never persisted, is this a limitation of the edge browser? or am i missing something?
I can set, and get the cookie straight after and it is never returned.
Copied below is the source for setting the cookie
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));var expires = "expires="+ d.toUTCString();
var path = "path='/'";
document.cookie = cname + "=" + (cvalue) + "; " + expires + "; path=/;";
Getting the cookie:
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);
}
if (c.indexOf(name) == 0) {
return (c.substring(name.length,c.length));
}
}
return "";
IE / Edge silently dropps cookies in the follwing situations:
On Top Level Domains, e.g. "example.com"
On Domain Names containing underscores, e.g. "my_sub.doma.in"
https://blogs.msdn.microsoft.com/ieinternals/2009/08/20/internet-explorer-cookie-internals-faq/
I have javascript popup it shows up per user (only once per day) and i need same popup but second.. when i try just to create second popup with same code it works like first one. if user saw first popup, he/she can't see other. please help here is the code
if (document.cookie.indexOf('_visited=1') == -1) {
var delay_popup = 1000;
setTimeout("document.getElementById('parent_popup').style.display='block'", delay_popup);
var date = new Date;
date.setDate( date.getDate() + 1 ); // Current date + 1 day
document.cookie = '_visited=1; path=/; expires=' + date.toUTCString();
}
I don't want them to work like 1 Popup
I just had this problem today.
what i did is this
enter code here
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);
}
}
var myCookie = readCookie('daycookie');
if (myCookie=''){
// code to show modal here
// then set an expiring token at midnight
var date = new Date();
var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
var x = Math.floor((Math.random() * 1000) + 1);
document.cookie = 'daycookie' + "=" + x + "; " + "expires="+midnight;
}
the logic is at first if the cookie does not exist show the popup
once the pop up shows it creates a cookie the expires at midnight and until next the day will the pop up show again.
i hope this will help you.
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
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.