In my asp.net application, am creating a cookie from server side using following code
Dim aCookie As New HttpCookie("StartDownload")
aCookie.Value = "True"
aCookie.Expires = DateTime.Now.AddMinutes(1)
Response.Cookies.Add(aCookie)
When I execute this code, the cookie is getting created, but am not able to delete the cookie from javascript on click of a button. Below is the javascript code.
function delCookie() {
alert(document.cookie);
document.cookie = "StartDownload" + "=; expires=" + new Date(0).toUTCString();
alert(document.cookie);
}
Am using IE browser. Not sure what the problem is. Kindly help.
You can try to hardcode the expiry date, something like, Thu, 01-Jan-1970 00:00:01 GMT and see if that'd work for you or not.
If still not, you might want to ask yourself following questions:
Have you checked the client-side and server-side cookie domains and paths to ensure they're the same?
Is one cookie secure and the other not?
Are there any server/client clock sync issues?
Related
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
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();
My coworker ran into an issue where NO cookie could be set on Chrome via code like this:
document.cookie = "TEST=1; expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
Putting document.cookie into the console immediately after would show results as if I made no change. On refresh of the page, the cookie was not there so it was reporting correctly, just not setting correctly.
The above code would work if he opened a new incognito window and worked for everyone else in general. I removed all his cookies using the dev tools and still had no luck manually setting cookies ( although others would come back that were set via the server headers).
Once he restarted Chrome, it started to behave properly, so it seems like he was running up against some quirk or bug that can no longer be reproduced.
Has anyone else run into this? As of now I am thinking of checking that document.cookie reports back what is expected after setting, and then initiating our cookieless flow for when a user has cookies disabled when things don't match up. I hate the idea of doing that so any suggestions / answers would be great.
The way cookies work, at least in Chrome, is a bit weird.
If you need to change a cookie's value, then you need to add/set each keys one by one.
Try this in your console:
document.cookie; // -> "expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
document.cookie = 'TEST=1';
document.cookie; // -> "TEST=1; expires=Tue, 14 Oct 2014 20:23:32 GMT; path=/"
Yes, it has added the key, and not replaced the whole cookie with TEST=1.
If you need to remove a key, you can simply provide no value: TEST=.
I hope this will get you out of the cookie nightmare (it was for me).
Make sure to run it on a server (at least a local server) so that document.cookie works.
If you locally run this file in the browser. "document.cookie" wouldn't work.
As another user mentioned, you have to set them one-by-one. These functions can be useful in parsing & applying a cookie string:
function clearCookies(){
var cookies = document.cookie.split(';');
for(i in cookies){
var vals = cookies[i].split('=');
var name = vals.shift(0, 1).trim();
document.cookie = name+'=';
}
}
function parseCookies(cookie){
clearCookies();
var cookies = cookie.split(';');
for(i in cookies){
var vals = cookies[i].split('=');
var name = vals.shift(0, 1).trim();
document.cookie = name+'='+vals.join('=');
}
}
You have to set the domain!
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;domain=" +
window.location.hostname;
}
The expiry date set for the cookie might be the problem. I have come into a problem like this before on Chrome. Set the date to present or future date and test if it would work. Probably that was how Chrome was designed.
We have the same problem in work a while ago, in our case it only happen when we work in local enviroment, after research we crossed an article that said that browser have some kind of problems with localhost:3000, because it recognizes as an insecure page or something like that.
We fixed just by replacing localhost:3000 for 127.0.0.1:3000 (i think that the ip depends on your configuration), and after we replaced that it works perfectly. I hope it helps you.
I'm having a bit of an issue deleting cookies in my JavaScript web-app. I've used this code in a separate function and it works just fine, but for some reason right now it doesn't actually change the expire time of the cookie for some strange reason, maybe I'm missing something obvious, but here's my code:
function deletetodo(obj) {
var checkboxID;
// get just the ID number of the checkbox.
checkboxID = obj.id.replace(/todo-status-/g, '');
// to make sure it's getting the right cookie ID (which it is)
alert(checkboxID);
// delete that cookie with the same ID number.
document.cookie = "todo-" + checkboxID + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
}
It's strange because in another function I have, this same code deletes a cookie, which then gets replaced with a small change at the end of the function.
Any ideas? Thanks!
Issue was with the path not being set. Since it's a single page app, I just added path=/; after the expiry date.
I had a project in my web design class this semester(I'm a newbie at this) and I've been working on a little side work in my free time. I've been trying to work with cookies and JavaScript. We didn't cover cookies very much in my class and I've been searching and searching for an answer to my current problem. Chances are, if you've ever responded to anything on this site about JavaScript and/or HTML, I've read it. As my title says, I'm having a problem where my cookie doesn't seem to save. On first load, the code works fine, then I reload the page and it doesn't recall the cookie value.
This is my cookie script:
var name;
if(document.cookie)
{
var q1=unescape(document.cookie);
var q2=q1.search("name");
if(q2!=(-1))
{
var n=str.split("name=");
var n1=n[1];
var n2=n1.split(";");
var q=n2[0];
name=q;
}
else
{
name=window.prompt("Please enter your name.");
document.cookie="name="+escape(name);
}
}
else
{
name=window.prompt("Please enter your name.");
document.cookie="name="+escape(name);
}
This is used once the rest of the page is loaded in:
document.writeln(name+"text stuff");
In the case of an incorrect value in the cookie, I've created this function that is called on via a button in the HTML:
function wrongPerson()
{
document.cookie="name=hooper; expires=Thu, 01 Jan 1970 00:00:01 GMT";
location.reload();
}
Sorry for such a long post, but I wanted to make sure the community had as much information as possible. Also, sorry about the poor formatting. I wasn't sure how to bring over my entire long thing of code and have the system allow it.
You need to set expire on your cookie script. If you don't put an expire date to your cookie it will recognize as a "one-time cookie". And after a reload or anything, it will disappear.
Set an expire to Wed, 01 Jan 2014 00:00:01 GMT
This is my personal opinion, but I rather use window.location.href = window.location.href; instead of location.reload();