Setting cookies' attributes for a website - javascript

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];
}

Related

GTM & Optimize : JS Variable is undefined but in console it works well

I'm trying to show the Google Optimize variant in Google Tag Manager.
I tried to implement it by "Custom JavaScript Variable":
function() {
var property = window.keys(gaData);
var experiment_nr = window.keys(window.gaData[property].experiments);
var experiment_value = window.values(window.gaData[property].experiments).toString()
if (experiment_value == "") {
return "0"
} else {
return experiment_value
}
}
This is the result of it:
Then I tried to test my code with a 5 sec delayed trigger:
And this is the result of the DevTools JS console:
As you can see, the console does not accept it with GTM but accepts it when I type it manually in.
Can someone help me there?
The answer was actually quite simple.
Google Optimize uses a cookie called _gaexp.
There, you get a string summing up the Google Optimize experiment ID as well as the version at the very end:
GAX1.2.wHL2IJUnSg2n8PB4iQH66w.18362.1
All I had to do was to create a new variable reading the cookie:
New variable
1st Party Cookie with the cookie name "_gaexp"
You can of course get the cookie name with JavaScript by simply calling Cookies.get('_gaexp') from the DevTools Console (to check if the cookie value is right)
The _gaexp value has to be manipulated to isolate the variant:
New variable
Custom JavaScript
Add the following code:
function (){
if ({{GA_Optimize_Variable}}=='undefined'){
return '0'
} else {
return {{GA_Optimize_Variable}}.charAt({{GA_Optimize_Variable}}.length-1)
}
}
The _gaexp is not existant when Google Optimize leads your traffic to the original variant of the website. Therefore, a if statement is needed.
Finally, you can use your variable in Google Analytics events and/or dimension.
Try to using dataLayer instead of window object.

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

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

Internet Explorer: expiration date for cookies doesn't work

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.

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();

Categories

Resources