Using IE11, I can display the content of all cookies, write out a cookie, find it, and delete it using JavaScript, even though I have my Privacy set to "Block All Cookies". (And actually, no matter what version I set my IE emulation to, the document.cookie still works.) It works as it should on Chrome with cookies disabled - i.e. document.cookie returns empty/nothing when I try to reference it in the same JavaScript.
I'm trying to detect whether the user has cookies turned off in their IE. (Old ASP app that requires IE with cookies. No JQuery. No Modernizr.) To do that, I'm attempting to write out a cookie, find it, and then delete it. That either works or it doesn't - which should tell me whether cookies are turned ON or OFF. Any ideas? I thought this was the safest way to detect a user's IE cookie setting.
My code:
<script language=javascript>
cookiesON = false;
if ("cookie" in document ) {
alert("1. document.cookie (before add): " + document.cookie);
var dateNow = new Date();
document.cookie = "testcookie=" + new Date()
alert("2. document.cookie (after add): " + document.cookie);
if (document.cookie.indexOf("testcookie=") > -1) {
cookiesON = true;
} else {
cookiesON = false;
}
// delete cookie: set cookie to expire 2 minutes ago
document.cookie="testcookie=xx; expires=" + (new Date(dateNow.getTime() - 2*60000).toGMTString());
alert("3. document.cookie (after delete): " + document.cookie);
}
On IE:
All 3 alerts show values for document.cookie, no matter whether cookies are turned on or off. You can see the testcookie being added and deleted back off.
On Chrome:
All 3 alerts show blank for document.cookie when cookies are off. Works as described for IE when cookies are turned on.
Related
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)
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
Step 1: My client from his OSX/Windows comes to my site using Google chrome , and downloads a trial key such as: LICENSE.cert file, which contains some unique keys: xyz-zsd-cdfd-xfdfd-1212
Step 2: i have a cookie written (for Step 1)
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
Step 3: NEXT day or Day after, again he comes back to the same site but this time he came from Safari or Firefox or IE (not using same Google chrome)
How do i read the cookie which was stored on his Google chrome in day 1? (is there anyway to write once for all? so that i suggest him?)
Cookies are managed separately by each browser - it isn't possible for you to access cookies created by other browser.
Your best bet would probably to persist the required data into some kind of database and access it when needed, if that's possible in your case.
I'm having a really strange problem and I'm looking for any possible ideas. I have a flyover that I load based on whether or not a cookie is found on the client's machine. In the flyover there is a 'No thanks' checkbox saying "Don't show again". I check to see if it has been checked like this in the flyover page:
$(document).ready(function() {
jQuery(window).bind("beforeunload", function(){ setCookieFO('noShowMerkleCpn','true',180); });
});
function setCookieFO(c_name,value,exdays){
if($('#noThanks').attr('checked') ){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}else{
}
}
I have ran the code in Firebug and verified that the cookie gets saved on document unload. I can even go into my cookies and find the cookie. Here is how I check for the cookie:
function runFancyBox(){
var idx = document.cookie.indexOf('noShowMerkleCpn');
if(idx < 0 ){
$('#cpnForm').click();
}else{
}
}
I don't really care about the cookie value. I just check to see if it exists and display the flyover if it doesn't. However, for some reason this check will return -1 even when the cookie exists.
Extra info:
The cookie is saved in my flyover.Html page under
server/bank/ima
The script that looks for the cookie is on the same server
server/bank/ima/script
The cookie is saved with this Path value with Host: server
/bank/ima/
Is there anything that jumps out that could be causing this issue? Any suggestions?
two things i would check. first, you are setting document.cookie without appending, so you wipe out all previous cookies (bad idea). second, make sure to set the cookie's domain and path to the same domain as the page reading it.
also be aware of your usage of the checked attribute:
if($('#noThanks').prop('checked'))
http://timmywillison.com/2011/When-to-use-.attr%28%29-and-.prop%28%29.html
I tried your code on both localhost and my server, and it works fine I assume you were careful to close your browser so that the cookie is actually set. My guess is you have a path problem, although from what you say about paths, it is certainly not obvious what it is.
I saved the code on my server, so you can at least examine code that works.
The url to set the cookie is: http://www.bridgesights.com/hondobridge/bbohondo/setcookietest.php
The url to test the cookie is: http://www.bridgesights.com/hondobridge/bbohondo/bbohondo_files/getcookietest.php
Although this has nothing to do with your problem, I highly recommend the jquery-cookie plugin for manipulating cookies. It is very lightweight and easy to use. The link is: https://github.com/carhartl/jquery-cookie
I'm stuck with this weird issue in Safari. I'm storing a user selection data in a cookie using javascript.
I create the cookie using following code -
document.cookie = cookieName +
"=" + encodeURIComponent(cookieValue) +
"; expires=" + jsDate.toGMTString();
and its read using -
var cookie = document.cookie;
if(cookie.length !== 0){
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+2,ind1));}
else { return '';}
This code works fine in Firefox and IE but when I access this cookie's data in Safari - an empty string is returned. The weird thing is, if i REPEAT my selection and try again, i can access the data. In other words, the first time i access my site, the cookie data is unavailable but in subsequent attempts the data is available!
To see this issue again, i have to clear Safari's cache, history and delete the cookies from the "Show cookies" section and reopen the browser.
Another observation - when i fail to read the cookie data, we can see the cookie when we look under Safari > Preferences > Security > Show cookies
ps:
facing this with Safari version 4 & 5