Cannot set cookie path to the root directory with Javascript - javascript

On localhost. Using Firefox 88.0 (Private window). My document tree:
/index.html
/page1/index.php
/page2/index.php
Here's my JS to set cookies (on page1):
function setCookie(name, value) {
document.cookie = name + "=" + value;
document.cookie = "path=/";
}
Which (I think) overwrites the cookie path to / every time I call the function. At the beginning of the same JS file I have: alert(document.cookie);. It displays the full cookie as I save it, including path=/.
On the homepage (/index.html) I have: <script>alert(document.cookie);</script>. But it displays an empty alert. I don't see the cookies. But if I go back to the page1 then I see the cookies again. Why is this?
I've also tried (solutions from other SO answers):
visiting 127.0.0.1 - didn't work (port is always 80).
Uploading to a web server. Same result as above.
visiting the localhost (localhost and 127.0.0.1) on Chrome.
Couldn't resolve. Could anyone help please? Thank you in advance!

Apparently I have to set the path at the time of setting the cookie, not using document.cookie after the cookie has already been set.
This got the problem fixed:
function setCookie(name, value) {
document.cookie = name + "=" + value + ";path=/"; //Set the path while setting the Value.
}

Related

JavaScript Duplicate Cookies

I'm using the Hapi framework for a Node.js application, and the Hapi framework comes with its own Cookie management tools, which i'm using for authentication.
The framework then sets a cookie named session, with a json value encoded to base64. The domain is set to example.com (not .example.com)
Now, the problem lies when i attempt to edit this cookie client-side, by doing the following
document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com";
This actually sets a duplicate cookie with the domain '.example.com'
I haven't asked Javascript to prepend the dot, and i cant seem to get rid of it.
I'm assuming that it is because of this dot, that the cookie is being duplicated. How do i set the domain without it automatically prepending a dot?
EDIT
I've given up on trying to remove the leading dot, and instead am trying to delete the old cookie and then create a new one. However i still end up with duplicate cookies!
Navigate to /login and enter login details
Redirected to /account and cookie set by server (WITHOUT Leading Dot)
Execute Javascript to delete and re-create cookie
1 cookie now exists and it has a Leading Dot before the domain
The above behaviour is good, however the following also happens, which is bad
Navigate to /login and enter login details
Redirected to /account and cookie set by server (WITHOUT Leading Dot)
Navigate to /example
Execute Javascript to delete and re-create cookie
2 cookies now exists, one with the leading dot(created by JS) and one without (created by server)
The code i'm using is
API.Session = {
Encoded : function () { return document.cookie.replace(/(?:(?:^|.*;\s*)session\s*\=\s*([^;]*).*$)|^.*$/, "$1")},
Decoded : function () { return JSON.parse(atob(this.Encoded()))},
Update : function (_decoded) {
document.cookie = 'session=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
document.cookie = 'session=' + btoa(JSON.stringify(_decoded)) + "; path=/; domain=example.com;";
}
}
API.Helpers.ShowAdvancedOptions = function () {
var s = API.Session.Decoded()
s.ShowAdvancedOptions = true
API.Session.Update(s)
}
Is by some chance the original cookie already present in this?
btoa(JSON.stringify(_decoded))
Cause from:
document.cookie
document.cookie is defined as:
a string containing a semicolon-separated list of all cookies
So it seems to me you are adding a new semicolon-separated value (new cookie) to that list (without removing the original cookie)
Ok, it's not that, have you tried this?
link
Sounds like the same problem you described
For anyone with a similar issue, this was eventually solved by dropping the domain property altogether. See other related question

Browser keeps multiple values for a single cookie name-value pair

We have a webshop. We use a cookie that stores the order ID of every single order/user. All of the items in the basket and the user's address info are related to that ID. The cookie is only meant to be changed when an order is complete or if its value is empty. We check the cookie with the server on each page load and only change it when conditions above are met.
A few months ago, we discovered that in some cases, the browser can keep multiple versions of that cookie value, and "switch" between those values randomly on page load. Moreover, the value is not overwritten - if the browser switches from value A to value B, a few page loads later it can load value A again. The browser can hold up to 5 (possibly more) values for a single cookie, and it keeps changing them randomly as the user navigates our webshop. It is very problematic since once the cookie value is changed - the basket contents changes with it. We experienced this problem primarily in Google Chrome and Internet Explorer. Trying to check the cookie value in the console shows only the value that is being used for the current page load.
We use the following function to set cookies:
function SetCookie(c_name, value, exdays){
var expires = "";
if(exdays)
{
var date = new Date();
date.setTime(date.getTime() + (exdays*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = c_name + "=" + escape(value) + expires + "; path=/";
}
Whenever I read about cookies, everyone says that overwriting a cookie with the same name and path is supposed to destroy the previous value. So I tried to do the following when setting the order ID cookie (delete cookie before setting it):
SetCookie(name , "", -1);
SetCookie(name , val, 14);
However, the problem still persists and the browser keeps randomly choosing the value on page load. What could be causing such behaviour? Is there any way to check the (shadow) values of the cookie that the browser is currently NOT using? Is there any way to check how many values for a specific cookie name and path the browser has stored?
EDIT: Our javascript order ID cookie setter function runs on page load. It is the only place we ever change the order ID cookie.
Recently, we tested this behaviour with dev tools open and it showed interesting results. A simple page reload can change the cookie header of the request to a request containing a different cookie value, before our cookie setter function ever had a chance to run. We thought it could be a caching issue (request being cached and used later), but it seems this behaviour persists when we set up the server to return a no-cache and no-store response header.
Look at the Nate answer to this question How to handle multiple cookies with the same name?
Hope it helps !!

Cannot retrieve javascript cookie after dropping cookie before redirect

My page HTML contains a span (with text) whose onClick = "goDropShip();"
The page contains a script that contains:
function goDropShip() {
var date = new Date();
date.setTime(date.getTime()+(24*60*60*1000));
document.cookie = "dropShip=true; expires="+date.toGMTString();
window.location.href="http://www.domain.com";
}
I have verified, with "alert()", that the function is in fact executing. And testing the cookie immediately after dropping it is successful. However, after the redirect, the cookie seems to be empty.
www.domain.com's index.html (which receives this redirect) has a script with the following:
if (document.cookie.indexOf("dropShip=true") >= 0 ) {
window.location = "http://www.domain.com/processDropShip";
}
However, the cookie appears to be completely blank after the redirect.
I am trying .indexOf() only because attempts to retrieve the cookie specifically by name have also failed, so I am trying to find the cookie in the entire document.cookie text.
I am probably just not using the cookies properly, or I do not know how to.
Forgive the fact that "dropShip" doesn't seem to make sense in this context, but I am having to obfuscate the details for security reasons. But the only thing I have changed is the cookie name.
As always, thanks for any help.
If the domain your are setting the cookie from and redirecting to are same, you just need to have the path set to / while adding the cookie so that it's accessible throughout the domain.
document.cookie = "dropShip=true; path=/; expires="+date.toGMTString();

Unable to set cookies in Javascript

I'm trying to set my cookies in Javascript the following way
<video id = 'media'></video>
document.addEventListener('DOMContentLoaded', function() {
document.cookie='X-At=$ACCESS_TOKEN$';
document.getElementById('media').src = "$some video link$";
});
However, the cookie just doesn't seem to be added. The file is also hosted on a simpleHttpServer because Chrome seems to ignore pages on local pages. Could someone tell me where the problem is? Note that the cookie gets set when I delete document.getElementById('media').src = "$some video link$";... SoI'm guessing it has to do with setting the source of the element.
Thanks so much.
Found out that cookies are domain specific. So I was unable to set the cookies for the request to a different network, i.e. my file is hosted on a local network 127.0.0.1 and I was trying to send the cookie to a different domain.
The hacky go around for this was to create a proxy server for my request and overwrite the cookie there and redirect the target to my original destination. Couldn't think of a better way to do this.
mate: way of create a cookie like this
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}

Are cookies stored in browser cache?

I'm running into a problem where Javascript I've written is getting an outdated cookie value. Each request made to the server should be updating the cookie with a the date the session will expire. But occasionally the date is in the past (which doesn't make sense because the page just loaded which renews the session).
So I'm wondering if the outdated value could be coming from the browser (Chrome) cache. Do cookie values get stored in the cache and then placed in document.cookie when the cached resource is utilized?
I'm reading the cookie via this code:
readCookie : function(name) {
var match = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)"));
return (match ? decodeURIComponent(match[3]) : null);
},

Categories

Resources