Internet Explorer: expiration date for cookies doesn't work - javascript

We are trying to set a cookie in order to use user auto login.
We are using an SPA with Reactjs + Redux + JavaScript (ES6),
To set the cookie we have created a component called CookieHandler which contains the set cookie function
setCookie(token = '', expirationDate = '1970-01-01T00:00:00') {
const expDay = new Date(expirationDate);
document.cookie = 'userToken=' + token + '; expires=' + expDay.toUTCString() + '; path=/;';
}
We also made sure that it's called once, just when is needed.
This works for all browsers expect in Internet explorer.
The problem is that IE sets the token in the current session but once we close the window and re-open it the cookie is gone, I also have tried to use toGMTString (which is deprecated) instead of toUTCString but still not working
Extra
We get the userToken and expirationDate from the back-end which its format is the same as the default value in the setCookie function
In all the other browsers works as expected even though we close the window.

Here I found some info that IE doesn't like "=" sign.
Maybe it's the problem?
Don't use "=" signs in your cookie names.
If you need them, use the single quotes to tell IE not to interpret it, but to accept it as a literal.

Related

Setting cookies' attributes for a website

The lack of experience I have has brought me here. I want to use cookies to save the user's theme, but I get this warning message in console:
'Cookie “” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute'
I have read some documentation and it says I should put this 'Set-Cookie: flavor=choco; SameSite=None; Secure' in my code, but I don't know where exactly, since it is not JS (which I use to GET and SET the cookies). So, what should I do to get over this problem?
Edit:
I use client-side JS only, I do not use any library, just plain and basic code. I set the cookies through document.cookie = some string and then splitting them apart with .split().
function setcookie(theme, page){
document.cookie = theme + ' ' + page;
}
function getcookie(value){
let str = document.cookie.split(' ');
return str[value];
}

JS Cookie doesnot available in server side?

This is how I create my cookie with Javascript and after that redirect to cart page.
var d = new Date();
d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
var expires = ";expires=" + d.toUTCString();
var product = { productId: btn.value, colorId: productColorId, quantity: 0 };
products.push(product);
document.cookie = "products=" + JSON.stringify(products) + expires + "; path=/; SameSite=strict";
window.location.href = "cart";
and I can find this cookie in my browser in cookie section, but in server side I get nothing.
At first I use this code and I get null.
string products = HttpContext.Request.Cookies["products"];
After that I try this code
if (HttpContext.Request.Cookies.TryGetValue("products", out cookieValue))
{
// TODO: use the cookieValue
}
else
{
// this cookie doesn't exist.
}
and always it runs else, It seems, even don't find cookie.
Is there any suggestion?
According to this documentation,a can optionally be set in double quotes and any US-ASCII characters excluding CTLs, whitespace, double quotes, comma, semicolon, and backslash are allowed.
Try the following changes in your javascript ,use encodeURIComponent() to convert double quotes
document.cookie = "products=" + encodeURIComponent(JSON.stringify(product)) + expires + "; path=/; SameSite=strict";
The screenshot of the cookie value got in the server-side
In response to a comment, Cookie headers in javascript is forbidden, which means it cannot be set programmatically. Only the browser may set it, and it may choose to not send cookie information along with the HTTP request depending on their browser settings. (Typically inside privacy settings)
First I would confirm that the cookie header is indeed being sent. You can usually find this out by using the browser's web inspector and looking at network request. Here is a screenshot in chrome:
If you don't see the cookie header then I would advise double checking browser privacy settings to ensure cookies are enabled and disabling ad/tracking blockers if you have them installed. If this is a case, unfortunately there isn't much you can do other than beg the user to change their settings or disable their ad blockers.
If you DO see the cookie header, then this suggest that it may be a problem in the back-end code, but I'm not familiar with ASP.NET so I can't really comment on that.
Hope this helps

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 !!

jQuery: remove a cookie when closing the browser (session cookie)

It sounds simple and I think it should be simple, but somehow I don't get it to work...
I want to set a Cookie using Javascript and this Cookie should be removed when the user quits the browser. Setting the cookie and getting the value is not the problem. But when I quit the browser and reopen it, the cookie is still there (Firefox).
I use jQuery and the Cookie-Plugin.
Here is my test code:
$(document).ready(function(){
$('#output').append( '<li>initialize...</li>' );
var $cookieVal = $.cookie('testCookie');
$('#output').append( '<li>check cookie...</li>' );
if(!$cookieVal) {
$('#output').append( '<li>set cookie...</li>' );
$.cookie('testCookie', 'eat cookies', { path: '/' });
//console.log( $.cookie() );
} else {
$('#output').append( '<li>cookie is already set...</li>' );
$('#output').append( '<li>cookie value: '+$.cookie('testCookie')+'</li>' );
}
});
Please find the working example at jsFiddle.
I am beginning to wonder if your testing method might be the problem here. So, I am going to write this in a specific way.
Actual Answer: Browser Setting
In Firefox, Options>General>When Firefox starts>"Show my windows and tabs from last time" is going to preserve your previous session. Change this setting to see that this is indeed working as it is supposed to. Firefox is prolonging your session. For further information, see this "bug": http://bugzilla.mozilla.org/show_bug.cgi?id=530594
There are similar settings in most browsers that probably behave the same way.
Original Answer:
I created a fiddle, http://jsfiddle.net/8Ahg2/ that uses document.cookie rather than jquery cookie plugin. Here is how you test this. (source below)
copy the following URL to your clipboard: http://fiddle.jshell.net/8Ahg2/show/
Completely close your browser of choice - this should be browser independent.
Open your browser, paste the url. The first time it should say: check cookie...
set cookie...
Refresh the page, notice that it should now say the value of the cookie ("test")
Close your browser completely again.
Navigate to the URL that should still be in your clipboard. *Do not refresh the page on the first view, it should again say 'check cookie...
set cookie...'
js
$(document).ready(function () {
$('#output').append('<li>initialize...</li>');
//this regex gets the "name" cookie out of the string of cookies that look like this: "name=test;var2=hello;var3=world"
var cookieVal = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1");
$('#output').append('<li>check cookie...</li>');
if (!cookieVal) {
$('#output').append('<li>set cookie...</li>');
document.cookie = "name=test";
} else {
$('#output').append('<li>cookie is already set...</li>');
$('#output').append('<li>cookie value: ' + cookieVal + '</li>');
}
});
There is some code that worked for me. It should expire when you close the browser because of the date to expire being before now:
var vEnd = new Date();
vEnd.setDate(vEnd.getDate() - 1);
var endOfCookieText = "; expires=" + vEnd.toGMTString() + "; path=/";
document.cookie = escape('testCookie') + "=" + escape("eat cookies") + endOfCookieText;
FIDDLE MODIFIED
Note that the fiddle gives a bunch of load errors on the console for me.

JavaScript cookie misconceptions

I'm using the following code for setting/getting deleting cookies:
function get_cookie(cookie_name)
{
var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
if (results)
return ( decodeURI(results[2]) );
else
return null;
}
function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure)
{
var cookie_string = name + "=" + encodeURI(value);
if (exp_y)
{
var expires = new Date(exp_y, exp_m, exp_d);
cookie_string += "; expires=" + expires.toGMTString();
}
if (path)
cookie_string += "; path=" + encodeURI(path);
if (domain)
cookie_string += "; domain=" + encodeURI(domain);
if (secure)
cookie_string += "; secure";
document.cookie = cookie_string;
}
function delete_cookie(cookie_name)
{
var cookie_date = new Date(); // current date & time
cookie_date.setTime(cookie_date.getTime() - 1);
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
but i am getting inconsistent results.
for example, a cookie set on the startpage (www.example.com/start) , will not always show up on a subsequent page (www.example.com/foo/thing.jsp).
i am setting a cookie "onUnload" of the page using
set_cookie("beginrequest", (new Date()).getTime(), null, null, null, "/");
and retrieving + deleting it "onLoad" via
loadDur = (new Date()).getTime() - get_cookie("beginrequest");
delete_cookie("beginrequest");
to measure the total amount of time the page took to load.
when using firebug, i often see "leftover" beginrequest-cookies and multiple instances of beginrequest with past timestamps.
how can i achieve to see just one beginrequest-cookie on every page?
If you're getting old cookies that might be because your page contains a lot of content and onload isn't called before onunload (because the page doesn't finish loading). So delete the cookie by calling something like this from both onload and onunload:
var deleted_cookie = false;
function delete_timestamp() {
if(!deleted_cookie) delete_cookie("beginrequest");
deleted_cookie = true;
}
You might also have a race condition if you're loading the next page quick enough that the 'delete_cookie' cookie hasn't expired properly, and your get_cookie implementation is picking that up. So try changing the regular expression in get_cookie to only pick up cookies with a value:
var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]+)(;|$)');
Also, if you're viewing the site in more than one window (or tab), their cookies can get mixed up, so don't do that. But try using a global regular expression to pick up all the values, and only using the latest one.
Echoing the other's suggestion to do some of the work on the server side - I've done this in the past:
1) Capture the time of request on the server side, and include a script tag with the time variable in the page:
<script type="text/javascript"> var start = 1224068624230;</script>
2) At the end of the page, in JavaScript, get a new time and calculate the total time.
Your code for set_cookie, get_cookie and delete_cookie seems to be correct. And your usage as well.
I think you should move this into your Java code - for me it seems an easier option than to hack this via cookies.
i agree with amix on both counts: your code looks ok at first glance, and this would probably be better handled by something on the server side.
regardless, at a guess, i'd say the issue you're running into at the moment is likely that the events aren't firing the way that you think they are. two ways you can clear up what's happening, are by making it visually obvious that the event is firing , and by increasing the verbosity of your output. any number of things could be interfering with the events actually firing: plugins, addons, keypresses, etc. if you open a new window (or an alert, or whatever) when the onload and onunload events fire, you'll be able to tell for certain that the functions are being called. likewise, if you store more data in the cookies, like originating URL, etc, you'll be able to better figure out which pages are generating the extra cookies.
i'd guess that one of your Firefox extensions is intermittently interfering with the onunload event.

Categories

Resources