Why can't I expire a cookie with JavaScript (not HttpOnly) - javascript

I've got a cookie being set in a framework I'm developing within via JavaScript (the framework appears to be using https://github.com/carhartl/jquery-cookie). I'm developing within this framework but don't have access to the framework code and I want to delete a cookie via JavaScript (I do not have access to anything serverside within this framework).
Inspecting the cookie via Chrome, I can tell a lot about it:
"domain": "www.example.com",
"expirationDate": 1667235180,
"hostOnly": true,
"httpOnly": false,
"name": "my_cookie",
"path": "/",
"secure": false,
"session": false,
"storeId": "0",
"value": "123456789"
It is hostOnly, but that should be fine as I am trying to remove from the same domain set in the domain field.
I'm trying to remove it using the following code:
function clearCookie(name, domain, path) {
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
clearCookie('my_cookie', 'www.example.com', '/');
When I do this however, it creates a new session cookie with a domain of ".www.example.com" (note the extra period) and doesn't delete the current cookie.
What am I missing?

Old question, but I just ran into this and discovered the issue.
If you have a hostOnly cookie, do not specify the domain when you modify/expire it.
Most cookie handling libraries will auto-specify the domain if one is not provided, making it difficult, if not impossible, to edit a hostOnly cookie.

I think there's a problem with how you're setting the expiration. Setting cookies with JavaScript requires a UTC/GMT format for the date. See this related answer:
Which date formats can I use when specifying the expiry date when setting a cookie?

You can't actually delete a cookie via javascript. What you do is set the existing cookie to expire and then allow the browser to handle its destruction. If you check the jquery-cookie source you can see that it actually has a function to destroy cookies that you could use here to simplify things.
The simple answer here is to use the existing frameworks remove function.
$.removeCookie(key)

Related

Browser can't show my cookie although I added it right before

I'm adding a cookie in my console with document.cookie = "newCookie=newValue".
Now I'm reading the cookie with document.cookie. But somehow the recently added Cookie don't appears.
I think there is something wrong with the way i'm reading the cookies out, because the console returns '' (I guess that means I don't have any cookies stored)
Not sure, but I think you have to add path and domain...
This worked for me on the chrome console while viewing mozilla.org:
document.cookie
'' // response:empty
document.cookie='yourname=yourvalue;path=/;domain=mozilla.org'
'yourname=yourvalue;path=/;domain=mozilla.org' // response: input string
document.cookie
'yourname=yourvalue' // response: cookie name and value
More details here: MDN Cookies

I have a wordpress site where a cookie is set determining what image/text to show on the front page. It works on mac always, on windows rarely

In snippets plugin, I have added the following code ;
add_action( 'wp_head', function () { ?>
<script>
function createCookie(cookieName,cookieValue,daysToExpire) {
var date = new Date();
date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + "; path=/; domain=humanistperspectives.org; secure";
}
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++) {
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
function getCookie(cookieName) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [key,value] = el.split('=');
cookie[key.trim()] = value;
})
return cookie[cookieName];
}
function delCookie(cookieName) {
cookieValue = "";
var date = new Date();
date.setTime(date.getTime()-(3600));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + "; path=/; domain=humanistperspectives.org; secure";
}
</script>
<?php } );
This sets a cookie and sets the file and title that displays on the front page of our site.
When I inspect the same page in browsers on my mac (safari, firefox, chrome), I see that the cookies are all set, expiring in september of this year.
Here are the values of the cookie:
Name: issuecover
Value: /wp-content/uploads/2022/03/220.jpg
Domain: .domain.org
Expires: Sept 5, 2022
Size: 45
HttpOnly: false
Secure: true
Samesite: None;
Last accessed: Tue, May 17, 2022
The same values appear in Windows in firefox, chrome and edge — but in Windows, despite having the same cookie values, the site doesn't seem to be able to access the cookies. So the magazine cover is a blank image and the title is blank, etc — but I see when I inspect that yes, in fact, the cookie is set just like on my mac.
It's just that on the mac, every browser is able to access the values and display the appropriate text/image and on windows, the same cookies are not accessible to the browsers.
Does anyone know if Windows is more picky regarding cookies?
NOTE: the site is on Cloudflare and strangely, if I purge the cache and force refresh in windows, the information in the cookie is accessible to the browsers.. but only at that time. If I come back a few hours later... despite seeing the cookies being still active in the browsers, the information in the cookies won't display on the page after the first time.
I appreciate any help here..thanks very much!
EDIT: I added code to add SameSite=Lax and on Mac, that shows up, but on Windows, SameSite=None still.
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString() + "; path=/; domain=domain.org; secure; SameSite=Lax;";
UPDATE:
ACTUALLY, I noticed there was a javascript error from another plugin and when I removed it, and purged the cache, the cookie's samesite lax status actually transferred over in Windows and the cookies were readable/accessible on the page. However, the true test is to check back in 1-2 hours and see if it's still behaving how I want. I'll come back with the details. THANKS.
BAD NEWS :
So going back to the site, the cookies AGAIN, despite being there, with samesite=lax, are somehow not accessible to the page and their values can't display.
httponly is false... it SHOULD show up. Why is this not working in Windows? Both Mac and Windows have the cookies properly stored but only on Mac do they appear on the page. HELP!
FINAL UPDATE
I've removed the cookies and used global variables to select different issues and relevant content.
For some reason, it seems like Cloudflare is caching cookies.
So thanks for your help everyone!
I removed all cookie-related code and ended up with a much simpler and faster code with global variables.
Thanks everyone!

Use javascript to delete all cookies not working

On a HTML page I use this javascript code to set cookies
this.store.setItem = function(name, value) {
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires;
};
I am trying to create a function that delete all cookies potentially set through the previous function. I found different threat about clearing cookies using javascript... This is an example of code that I have tested
deleteAllCokies : function() {
var res = document.cookie;
var multiple = res.split(";");
for(var i = 0; i < multiple.length; i++) {
var key = multiple[i].split("=");
document.cookie = key[0]+" =; expires = Thu, 01 Jan 1970 00:00:00 UTC";
}
}
The code works perfectly on computer running uptodated browsers. However when I try the code on older Browser( I runned the page as a webOS app) I get an error while trying to delete the cookies
SecurityError: DOM Exception 18: An attempt was made to break through
the security policy of the user agent.
Someone has an idea about the problem?
The other browser may have other cookies created by other sources that your script doesn't have permission to delete. Try to dump all the cookies in the console.log to verify this.
I've saw this error in webos 1.x and 2.x. If your application is stored locally (built-in the ipk) the protocol to access the document is forced file:// by the OS. You can check this thread
LG recommends to use webStorage or serve your app by a webserver
PS: A hosted web app will use the HTTP/HTTPS protocol to access the document

Cookie not being set in Safari, ios but works in ie, ff, chrome

I was alerted that when items are placed in our shopping cart using safari/ios, they are not showing up. The cart cookie is not being set. It is set by a redirect page. I saw the issue about safari not setting a cookie and redirecting, but if I take out the redirect, it is still not getting set. Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>
<script type="text/javascript">window.onload= function() {
SetCookie('RORDERID','OECLICK*17180*39521',10);
setTimeout("redir()",100);}
function redir(){window.location = 'http://www.shopthethirdfloor.com/forward-to-ttf-cart.html';}
function SetCookie(cookieName,cookieValue,nDays) {var today = new Date();var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();}</script>
</head>
<body><br>If you are not redirected to the shopping cart, click here</body></html>
I thought maybe the setTimeout would allow it to work, but if I take out the call to redir() it still does not set the cookie.
Any suggestions?
Additional notes: I found a posting about this, and updated the code to:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>
<script type="text/javascript">window.onload= function() {
setCookie2('RORDERID','OECLICK*17180*43',10,'','','');
//setTimeout("redir()",100);
}
function redir(){window.location = 'http://www.shopthethirdfloor.com/forward-to-ttf-cart.html';}
function setCookie2 (name, value, nDays, path, domain, secure) {var today = new Date();var expires = new Date();
expires.setTime(today.getTime() + 3600000*24*nDays);
var curCookie = name + "=" + encodeURIComponent(value) + (expires ? "; expires=" + expires.toGMTString() : "") + (path ? "; path=" + path : "") + (domain ? "; domain=" + domain : "") + (secure ? "secure" : "");
document.cookie = curCookie;}</script>
</head>
<body><br>If you are not redirected to the shopping cart, click here</body></html>
and it works, but still does not work on my site. This code is being ran in an iframe from a different domain on my site. The site is www.shopthethirdfloor.com. If you go to products, select a product and add it to the cart, it does not add a cookie on safari, but does the other browsers.
ok, after a lot more digging and trial and error, it was the issue where safari would not set a cookie in an iframe cross domain. I tried several suggestions on the web including here, but they either were not relevant or did not work (were old). I found that I had 2 options. The first, change the framed domain to be a sub domain of the parent window domain which I could have done, but would have needed to change umpteen links and the payment gateway which I did not want to do. The second, took several steps, but works excellent is as follows:
The page that is trying to set the cookie checks if it is a safari browser and if it is, changes the window location to a php script on from the same domain as the browser passing the cookie in a get variable, this in turn changes the window location to an asp script from the iframe server sending it the cookie informtion which has the cookie setting code and after setting the cookie, loads the page for the the shopping cart.
The key here is getting the cookie setting page that needs to set the cookie into the parent window and then load the new destination page.
This has a few steps, but works well.
try to use HTML5 local storage concept to achieve cookie storage in safari browser
Default safari settings will be Cookies enable for trusted sites ,so you must enable the settings to enable cookie storage... TO overcome this issue you can use HTML5 local storage concept

remove cookie using javascript / jQuery

I have a little demo page to show the effect of a website depending on different user cookies.
Then I set the click() function of some div to use the plugin jquery.cookie.js which provides 2 functions:
$.cookie('name', 'val')
$.removeCookie('name')
after I called $.removeCookie(), I call window.open('new page') since I need to go to the content. but httpliveheader always shows that it's not removing the cookie in question.
OK, I found it, it was because the cookie set by my backend code and front end JS are in different path.
my java spring MVC controller has an access path of /MyPath/Blah/ in the code I just did
httpServletResponse.addCookie(new Cookie("something", "something"));
this turns out to default to the path where the code sits under , i.e. /MyPath/Blah/
but the JS sets something like $.cookie("something", "somevalue"), it goes to root. that's why I am seeing 2 different values in httpLiveHeader dump. unfortunately the path thing is controlled by browser, so it doesn't show up on liveheader dump. I only found this after I inspected the "remove cookie" window in mozilla
//for example :
document.cookie = "cookie_name=" + encodeURIComponent(cookie_value) +
"; expires=" + expires.toGMTString() +
"; path=/";
you need to set PATH.

Categories

Resources