Same cookie, different values between ColdFusion and JavaScript - javascript

I am running into a problem with a cookie I want to access with both JavaScript and CF. I can create the cookie with JavaScript, like so:
document.cookie = 'SAVEDLISTINGS='+newc + ';path=/';
and on the next page CF can see it fine. However, if I use the same JavaScript to update the cookie with a new value, CF will not detect the change on subsequent pages. It retains its original value, as evidenced by the debug output and by dumping the Cookie scope.
JavaScript continues to see the correct cookie value, which I can check using Firefox developer tools. I assume this means the cookie file is being correctly updated. I do not see two cookies with the same name: only one, and it has the value as manipulated by the JavaScript.
I can delete the cookie in JavaScript, using
document.cookie = 'SAVEDLISTINGS=; expires=Thu, 01 Jan 1970 00:00:00 UTC' + ';path=/';
and this will delete the cookie from CF as well (on subsequent pages).
Note that I am not actually using CFCookie to manage the cookie, but I have experimented with setting it blank by ColdFusion (with httponly=no). This doesn't seem to make any difference.

Set the domain value of the cookie to make sure you are getting/setting the same exact cookie. You can view that info with Firebug. You can see below how two cookies named "testName" are treated as separate entities based on the domain. This is important so different sites can have the same cookie names without overwriting each other.

Related

How do I make a cookie available in app.domain.com/* when the cookie is created in domain.com?

I am trying to write a PoC in a website. I created a cookie storing some information in domain.com, and wish that the cookie is also available in app.domain.com/*. However the MSDN docs about domain in cookies is not very clear about this. Is that by any means possible using javascript?
document.cookie = `Code=${code.toString()}; expires= #${someDateObj}; path=/; domain=domain.com`
Expected results:
After the cookie is made available inside domain.com, when I go to anywhere inside app.domain.com/* and domain.com/* the cookie is still available for fetching.

Can't remove duplicate cookie

I created a custom UI for the google translate javascript plugin by adding some buttons and then setting the googtrans cookie when the user selects a language. This works totally fine locally. However I noticed when I put it on a live site, the cookie gets set and then a duplicate cookie appears that overrides the one that I've set.
Duplicate Cookie
The mystery cookie seems to be the domain with a dot prepended to it. I've tried adding the dot to my cookie's domain, but that doesn't work and according to the docs, that dot will be ignored anyway.
I've tried just clearing the cookie manually through the Chrome console
document.cookie = "googtrans=; expires=" + new Date + "; domain=.domain.org; path=/";
and that does clear the cookie that I set, but leaves the duplicate cookie unchanged.
Anyone know a way of nuking all of the possible cookies or something? It's so strange that it only does this on a live site.
Nevermind, I randomly figured it out right after posting this. If I set two cookies, one WITH and domain and one WITHOUT, the one without a domain will write to the .domain.org cookie.
document.cookie = "googtrans=;" + new Date + ";path=/;domain=domain.org";
document.cookie = "googtrans=;" + new Date + ";path=/;";
I don't know why, because the documentation says that NOT specifying a domain means that subdomains are NOT included, which is what the dot prefix was originally for.

Expiring a cookie on page unload, then setting cookie on next page load

I am setting a cookie animals via setcookie('animals, json_encode(array('tiger')), time()+(3600*24), '/'); in PHP when a page is requested.
I am then expiring the cookie on page unload with:
window.addEventListener('unload', function() {
document.cookie = 'animals=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
});
This sets the cookie to be expired. This works great.
The problem is that when I refresh the page, setcookie() tries to set the cookie, but the browser has the cookie set to be expired, so the browser deletes the cookie when PHP comes back instead of using the new data/expiration time. So the cookie is deleted and I'm not able to access animals after the page has loaded.
This happens in both FF and Chrome. The problem is only on page refresh; if I go to a different site and then come back, or come to the page for the first time, the cookie is properly set.
Is there any way I can get the browser to understand not to delete the cookie, and instead use the new parameters? When does the browser decide to the delete the cookie, and why doesn't it look at the new params coming in from PHP?
Possible solutions (I would call them "hacks") are to add a unique identifier to each cookie (i.e. a timestamp) so animals-1407435704, so that each page load has it's own cookie. I could also echo out a document.cookie from PHP that sets the cookie, so after the page loads, the JS sets the cookie. But, I would rather see a solution that instructs the browser not to delete the cookie.
Update: I'm going with adding a unique identifier to each cookie, because I actually need to anyway to account for multiple tabs being open (and allow them to each exist on their own). I'm going to leave the question open because I don't understand why the browser does this.
I think this solution should reset the cookie:
document.cookie = 'animals=; Max-Age=0'
What you can do is to check and see if the cookie exists and then react accordingly.
If the cookie still exists on a fresh load, keep checking on a delay until deleted, then add it again:
waitToSetCookie(){
if (checkCookie(animals))
setTimeout(waitToSetCookie(), 1000);
else
setcookie('animals, json_encode(array('tiger')), time()+(3600*24), '/');
}

Setting Multiple Cookies with Javascript

I created a simple page that lets you make cookies and displays them by appending them to a text area. My understanding is that you can create as many cookies as you want simply by calling
document.cookie = ...
However, when I print out my cookies, only 3 of them are ever displayed. It also appears that I'm not appending the cookies to the text area properly, because these values never change.
To test if this was a problem with the cookie creation, I used an alert popup box to notify the user when their new cookie is created. This shows me that the cookies ARE being created. So, I don't know why I can only see three of the cookies in the display.
Here is the code:
EDIT: code removed because answer is closed.
How can I fix this so that all the cookies created are appended to the text area? Thanks.
When you set a cookie via document.cookie you provide a key\value pair in the form key=value.
In your code you are always passing a key of "name" so rather then creating a new cookie you're just updating the same cookie every time. You need to find a way to generate a unique identifier to use as the key for each new cookie (perhaps a count will do)
Also you shouldn't need to append the value from document.cookie to the text as document.cookie will return the values for all cookies so you can just set the value of document.cookie to the value of you text area.
More info on document.cookie

Cookie is set twice; how to remove the duplicate?

So I have a website that uses a cookie to remember the current layout state across visits. Everything was working great until I added a Facebook 'Like' button to the site which generates links that allow users to share a certain UI state (a little confusing but not really relevant to the problem).
The problem is that when I visit the site via one of these Facebook links a second copy of my layout cookie seems to be created (as in, I see two cookies with the same name and different values). This wouldn't be too terrible except that the value of the duplicate cookie appears to be stuck, coupled with the fact that when the user returns to the site the browser remembers the stuck value instead of the most recently set value (so it's kind of like there's a "good" cookie that I can still work with, and a "bad" one which I cannot, and the browser likes to remember the "bad" cookie instead of the "good" cookie). This breaks my layout tracking/remembering functionality.
So there are two questions here:
How do I stop this from happening/why is this happening in the first place?
How do I fix things for any users that already have a stuck cookie (I know I could just pick a new name for the cookie, but I'd rather do it by finding a way to properly unstick the stuck cookie)?
If I use Chrome's developer console after visiting the page in a stuck state, I can see that document.cookie is (formatting added for readability):
layoutState=[{'id':6,'x':8,'y':1525,'z':4,'url':'undefined'}, {'id':1,'x':625,'y':709,'z':2,'url':'undefined'}, {'id':2,'x':8,'y':37,'z':3,'url':'undefined'}, {'id':3,'x':625,'y':1179,'z':5,'url':'undefined'}, {'id':4,'x':626,'y':37,'z':1,'url':'undefined'}, {'id':5,'x':626,'y':357,'z':1000000,'url':'http://m.xkcd.com/303/'}];
WibiyaNotification1=1;
WibiyaNotification213286=213286;
WibiyaNotification213289=213289; wibiya756904_unique_user=1;
JSESSIONID=DONTHIJACKMEPLEASE;
WibiyaProfile={"toolbar":{"stat":"Max"},"apps":{"openApps":{}},"connectUserNetworks":[null,null,null,null,null,null]};
WibiyaLoads=59;
layoutState=[{'id':6,'x':8,'y':1525,'z':4,'url':'undefined'}, {'id':1,'x':625,'y':709,'z':2,'url':'undefined'}, {'id':2,'x':8,'y':37,'z':3,'url':'undefined'}, {'id':3,'x':625,'y':1179,'z':5,'url':'undefined'}, {'id':4,'x':626,'y':37,'z':1,'url':'undefined'}, {'id':5,'x':626,'y':357,'z':6,'url':'http://m.xkcd.com/303/'}]"
Ignore the Wibiya cookies and the JSESSIONID. The stuck cookie is the first 'layoutState' instance, and the one that I can still manipulate in JavaScript is the second 'layoutState' instance. Here is what I get if I change some things around:
layoutState=[{'id':6,'x':8,'y':1525,'z':4,'url':'undefined'}, {'id':1,'x':625,'y':709,'z':2,'url':'undefined'}, {'id':2,'x':8,'y':37,'z':3,'url':'undefined'}, {'id':3,'x':625,'y':1179,'z':5,'url':'undefined'}, {'id':4,'x':626,'y':37,'z':1,'url':'undefined'}, {'id':5,'x':626,'y':357,'z':1000000,'url':'http://m.xkcd.com/303/'}];
WibiyaNotification1=1;
WibiyaNotification213286=213286;
WibiyaNotification213289=213289;
wibiya756904_unique_user=1;
JSESSIONID=DONTHIJACKMEPLEASE;
WibiyaProfile={"toolbar":{"stat":"Max"},"apps":{"openApps":{}},"connectUserNetworks":[null,null,null,null,null,null]};
WibiyaLoads=59;
layoutState=[{'id':1,'x':8,'y':39,'z':1000000,'url':'undefined'}]
The second 'layoutState' has the correct information that I want the browser to remember. However what the browser actually remembers is the value of the first instance.
I've tried unsetting the cookie entirely, which causes the second instance to disappear, but nothing I do seems to get rid of the first instance. I get the same behavior in all major browsers (Chrome, Firefox, IE), which makes me suspect that I must be doing something fundamentally wrong here, but I'm not sure what it is.
You can view the site itself here. Or click here to access it via a Facebook link (should generate a stuck cookie). Any help is much appreciated.
Update:
So the steps to reliably reproduce the error are as follows:
Visit the site via the Facebook-style link
Make some changes to the layout, and then close the tab.
Visit the site via the normal URL.
Your layout from the initial visit should be correctly remembered, so change some things around and then refresh the page. When the page reloads, your changes will no longer be remembered.
I've also noticed that revisiting the site via the Facebook-style URL is able to clear/reset the stuck cookie. So it's like the browser is keeping a separate cookie for each URL path, or something, and not allowing the root page to access the cookie that was set on the other URL path. I thought I might be able to fix this by explicitly setting path=/ on the cookie, but no dice.
Update 2:
I've found that if I set both the path and the domain of the cookie I get different behavior in all browsers:
Firefox - Works correctly now, hooray! Worked correctly once, then broke, boo!
Chrome - No change
IE - Seems to be keeping separate cookies for each URL, so the Facebook-style URL remembers one state, and the standard URL remembers a different state. Both update correctly and independently of each other. This is kind of funky, but still way better than the stuck/broken state.
Dude(tte), there are inconsistencies, and a bug, in your cookie setter.
1. Make sure path and domain is correctly set
The path and domain should be the same for both clearing the cookie and setting it. See your code here:
document.cookie = c_name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
and compare it to:
var c_value=escape(value) + "; expires=" + exdate.toUTCString(); + "; path=/spring; domain=aroth.no-ip.org";
you will see that the setter has both of them, but the deleter doesn't. You will bring about chaos.
2. Oh, and that nasty semicolon
That second line of code I quoted above, has a semicolon introduced in the middle of a string concatenation expression. Right after exdate.toUTCString(). Kill it. Kill it…now.
At least on my Google Chrome, I managed to get it run correctly, if I set a breakpoint at json = "[" + json + "]"; and modify setCookie before it is executed.
P/S: It was a bizzare debugging experience, where I managed to set 4 layoutState cookies, by fiddling with path & domain.
This may be too simple, but just in case, are the cookies recorded for two different paths? If the URL is different, you may be setting your cookies for a restricted path, so the system would take them differently.
Here is a solution, the / slash help to do not set duplicate cookie of same name
setcookie('YourCookieName','yes', time() + 400, '/');
check in Chrome console -> Resources if your page gets loaded twice. That would be the reason of double cookie.
There is again the problem left after identifying the problem and taking prevention by correctly setting the cookie.
You also need to delete previous incorrectly set cookies in your or in your client's browser.
So observe the cookie set from developer tools and search for path and subdomain and put those explicitly on your code to delete.
function eraseCookie(c_name) {
document.cookie = c_name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}
function eraseCookieWithPathDomain(c_name) {
document.cookie = c_name + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;path=/yourpath/to; domain=sub.domain.com";
//you can remove this function call on your second upload if you are confirm that the previous cookie setter expired
}
You may need to call function eraseCookieWithPathDomain right after eraseCookie or even every time after document load depending in your application.
You can add the following key in the AppSettings in the web config file it solves the issue of duplicate cookie.
<!-- Tell ASPNET to avoid duplicate Set-Cookies on the Response Headers-->
<appSettings>
<add key="aspnet:AvoidDuplicatedSetCookie" value="true" />
</appSettings>
This will help avoiding the duplicate Set-Cookie() in Response Headers.
It seems the issue is not a duplicate cookie (cookies overwrite themselves) but a duplication of the DATA in your cookie.
I think you'll have to modify the script that reads the cookie and clean out the duplicate value if it's detected.

Categories

Resources