Javascript cookie not being set [duplicate] - javascript

The following code works fine in FF:
var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "c_odi" + "=" + $('#orderdetailid').val() + expires + "; path=/";
But not in Chrome. When I'm using Chrome and I do document.cookie in the console to view cookies, the c_odi cookie isn't there. But when I do the same in FF, it is. How can we make cookies work in Chrome? The cookies that were added by PHP are fine, but not this one in JavaScript, and I do need to add this cookie via JavaScript at this point.

This problem can occur if You open Your code as file:///C:/.../xxx.html instead of http:// localhost/xxx.html. Chrome doesn't save cookies (because there is no domain and no http communication) in file:// case.
Few links of interest:
https://gist.github.com/shellscape/02d3a97031e7afdf99d2642f93d59486
Setting Cookies using JavaScript in a local html file
https://bugzilla.mozilla.org/show_bug.cgi?id=536650
https://datatables.net/forums/discussion/46255/save-state-to-cookie-in-file-protocol

Chrome doesn’t store cookies from the pages which are loaded from local file system. For example if you are accessing a HTML file in chrome browser from local file system(ex: file:///C:/Users/deepak.r/Desktop/test.html), cookies are not supported.

Try to replace this line:
document.cookie = "c_odi" + "=" + $('#orderdetailid').val() + expires + "; path=/";
with this one:
document.cookie = "c_odi" + "=" + escape($('#orderdetailid').val()) + expires + "; path=/";
You would have to use unescape when you try to read value, but you'll menage when time comes :)

Seems like it's working for me:
http://jsfiddle.net/rQEnF/3/
At least the cookie shows up in dev tools, as you can see. However, I replaced the jQuery selector $('#orderdetailid').val() with a constant value, as you can see. Is there something wrong with that value or the element containing the value maybe?

Make sure your address bar url matches the domain. In Chrome if you set domain=www.site.com and then test your page in the browser missing out the www. it won't work.

Related

Persistent cookie being deleted as soon as Safari is closed and reopened (working fine in Chrome, Firefox)

I'm using the following JavaScript code to store a cookie with a ID in the browser of the website visitor for 60 days.
While it is working perfectly in Chrome, Firefox etc. in Safari the cookie disappears after closing and reopening the browser. (happens with iPhones, Macbooks etc., even in the standard cookie-configuration)
function setCookie() {
const date = new Date;
date.setDate(date.getDate() + 60);
var uid = Date.now().toString(36) + Math.random().toString(36).substring(2);
document.cookie = "ck=" + uid + "; expires=" + date + "; path=/";
}
Does anyone have an idea, why this could be happening? Greetings!
I decided to set and read the cookie with php, now it is working. Maybe that is the better option anyways, since cookies set with document.cookie can only last maximum 7 days in Safari, before they get automatically deleted
(according to this overview)

Can't set Cookie with JavaScript in Safari or iOS

I'm working on some cookie consent and terms etc.. So I made a JS function to set a cookie after user clicks "Agree" button:
...html
<button onclick="setCookie('law_cookie', 'agree_all', 90)">
...js
function setCookie(name, value, daysToLive) {
// Encode value in order to escape semicolons, commas, and whitespace
let cookie = name + "=" + encodeURIComponent(value);
if (typeof daysToLive === "number") {
/* Sets the max-age attribute so that the cookie expires
after the specified number of days */
cookie += ";max-age=" + (daysToLive * 24 * 60 * 60) + ';Secure;path=/';
document.cookie = cookie;
cookie_set = true
}
}
Now I tested in chrom and firefox, everything works great! BUT, safari isn't able to set a cookie. I tried to initialise by clicking on the button but after reload safari hasn't set the cookie.
I checked if javascript was enabled (it was) and I also tried to set cookie = encodeURIComponent(cookie); but nothing works.
Someone has an idea what I'm doing wrong?
Safari version 15.2, unlike Chrome and Firefox, refuses to set Secure cookies on the localhost origin, so you'll need to add a workaround just for Safari.
Have you tried using a private tab on safari? It may be possible that it didn’t load your new files. On my website I use the same method to write cookies and it works on Safari.
Encoding the value is good
let cookie = name + "=" + encodeURIComponent(value);
But encoding the whole sting not:
cookie = encodeURIComponent(cookie);
I modified your script I removed the 'secure' entry as that will limit it to working only with HTTPS, when you are troubleshooting give it the best chances, and add security only when everything works. In the past the might have worked with some browsers:
https://developer.mozilla.org/en-US/docs/web/api/document/cookie
;secure Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains.
And I added window.alert so you will see 3 things:
Proof that your button/event actually hit
Check that you provided the age argument (without age your condition will not save cookie)
Will show you what values are going to save so you can confirm if it's ok.
The modified JS:
function setCookie(name, value, daysToLive) {
// Encode value in order to escape semicolons, commas, and whitespace
let cookie = name + "=" + encodeURIComponent(value);
if (typeof daysToLive === "number") {
/* Sets the max-age attribute so that the cookie expires
after the specified number of days */
cookie += ";max-age=" + (daysToLive * 24 * 60 * 60) + ';path=/';
window.alert(cookie);
document.cookie = cookie;
cookie_set = true
}
}
setCookie('law_cookie', 'agree_all', 90)
Often using a lot of console.log helps with troubleshooting as well
Do you use some other frameworks which could interfere with this? Something might be doing stuff with cookies behind your back. Did you try saving cookies from the HTTP header as well?
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
Did you try to minimalize the replicator, make smallest project which can still replicate the problem? Or start with a small self-contained JS fiddle:
https://jsfiddle.net/ao9p7e4j/1/
Here I added a function to show cookies to see what you have

Setting Cookie in javascript and reading it in PHP

So I have a cookie set through js when the user accepts a popup, it is set through the following function.
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 + ";path=/";
}
setCookie("accepted_popup", 'accepted_value', 1);
When checking the Cookie in chrome dev tools it is set indeed.
Name |Value |Domain |Path |Expires |Size |HttpOnly |Secure |SameSite |Priority
accepted_popup |accepted_value |example.com |/ |2020-07-09T15:07:43.000Z |11 | | | |Medium
I realize that for the cookie to take effect on the server it would need a page load. So I don't want the popup to show next time the page loads, so I'm checking the Cookie on the server like this.
<?php
if(isset($_COOKIE['accepted_popup'])){
doSomething(); //not showing popup
}else{
showPopup(); //showing popup
}
?>
What's new in this question that hasn't been asked before is that the above code was perfectly working on the old server, it stopped working when moving to AWS(if that might be a reason).
When I do var_dump($_COOKIE); on the server the cookie accepted_popup doesn't show in it.
Also I'm setting the cookie and retrieving it on the same domain(in production), say "example.com" no subdomain or www.
On my development site subdomain.example.com the above code is working fine, and behaving as expected.
So the problem turned out to be not in setting the cookie in PHP but in AWS CloudFront.
If anyone is facing the same problem and have AWS hosting, check
CloudFront Distributions -> Behaviors -> Default(*) either change the "Forward Cookies" option or set add the cookie names to the "Whitelist Cookies" as shown in the image.

Javascript cookies creation

When creating a cookie using javascript using document.cookie
document.cookie = name + "=" + value + "; " + expires + ";path=/";
will the domain be populated or do I need to specify it?
You can only create cookies for the domain that your script is running under. So yes, the browser will set the cookie for the proper domain.
It will be populated.
You can run this in the console and then look at the cookies and Domain will be populated.
document.cookie = "val=val;Session;path=/";

A question about window.open and cookie

Say I have two apps, www.test.com and sub.test.com, now in sub.test.com, I create a window to load www.test.com with codes like :
window.open('www.test.com');
So the window just popup and load www.test.com successfully.
Then I set a cookie in sub.test.com, say "uname=wong2;domain=.test.com", I've learned that with set to domain=.test.com, all sites with domain test.com(such as www.test.com, aaa.test.com, test.com) can read the cookie.
But when I try to load the cookie from the window that just popup with www.test.com, it can't get it.
Then I found that if I don't use window.open but directly open www.test.com in browser, it works.
So is there some restrictions on window.open and cookie?
just check how you set the cookie:
var domain = 'test.com';
var expires = (function(days){
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
return date.toUTCString();
})(5);
var name = 'myCookie';
var path = '/';
var value = 'foo';
document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expires + "; path='" + path + "'; domain=" + domain + ";";
That is called cross domain and you cant set cookie in one domain and try to access that in different domain. Browsers wont allow doing this.I think you can accomplish this using iframe or same origin policy or try using document.domain I am not sure what you want to do exactly.

Categories