Why document.cookie is not working - javascript

var curCookie = name + "=" + value +
"; expires=" + ATS_getExpire() +
"; path=" + path +
"; domain=" + domain ;
document.cookie = curCookie;
alert("Your Cookie : " + document.cookie);
When i use above code the alert message coming as empty. Why document.cookie is coming as empty.
Please anybody answer.

See here for a Live Example
You're using ; instead of ,.
Use , to deliminate your cookie values
var curCookie = name + "=" + value +
", expires=" + ATS_getExpire() +
", path=" + path +
", domain=" + domain;
document.cookie = curCookie;
alert("Your Cookie : " + document.cookie);
UPDATE
As of today (2021-08-25), the live example is not consistent accross browsers:
Chrome 92.0.4515.159: ❌
Edge 92.0.902.78: ❌
Opera 77.0.4054.277: ❌
Firefox 91.0.2: ✅

I found that ... frustratingly, document.cookie doesn't work when running the page locally in one's browser.
When I uploaded the same page to a website, suddenly all the cookie values worked just fine. I will find out why this is and fill the rest of this answer out later.

Sometimes this can occur if the page is hosted on a domain listed on the public suffix list (e.g. github.io, cloudfront.net). These domains are treated specially by the browser and restrict writing cookies for security reasons.

Try using jQuery Cookie plugin:
jQuery Cookie plugin
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

Related

JavaScript cookies not working on sub-domains

I have a cookie authorization banner, with a button labeled 'Got it!' that dismisses it. I do that by setting a cookie.
To set a cookie, I have this in my <head>:
<script>
function setCookie(cname, cvalue, exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
var domain = ".brokenhearts.ml";
var security = "secure";
var location = "/";
document.cookie = cname + "=" + cvalue + ";" + expires + ";" + location + ";" + domain + ";" + security;
}
</script>
and I've set this to be executed when the button is clicked:
var privacyValue = "yes";
setCookie("privacy", privacyValue, 365);
The problem is, when I check for the cookie in Chrome, it shows me something like this:
As you can see, the cookie is getting set only for www.brokenhearts.ml and not for its sub-domains. I want the cookie to be set for all sub-domains.
I tried setting the cookie with the domain as "brokenhearts.ml" and it still gets set only for www.brokenhearts.ml.
When setting up the cookie, your domain must be in format of .domain.com – dot and root domain and path=/, always.
If you don't set path=/, auto path will be saved as from where the cookies is being saved - hence it wont be accessible across any subdomain.
//variables
var LastReportGenerated="Jul 11 2013",
baseDomain = '.cssjunction.com',
expireAfter = new Date();
//setting up cookie expire date after a week
expireAfter.setDate(expireAfter.getDate() + 7);
//now setup cookie
document.cookie="Report={'ReportName':'MainReport', 'lastGenerated':" + LastReportGenerated + "}; domain=" + baseDomain + "; expires=" + expireAfter + "; path=/";
Source:
How to set cookies to share across all subdomains using JavaScript

document.cookie can't be set in Chrome

I want to save a cookie using simple javascript. So I went to w3 and they have a ready made function to save a cookie. When I tried this code in firefox it worked exactly as expected, but in Chrome setting the cookie had no effect. I saw other questions on this site where the cookie was deleted because of a lack of expiredate, but I both set a date for a few days later and document.cookie never gets set. I walked through the code line by line in the debugger, but the value of document.cookie stayed an empty string even right after the line :
document.cookie = cname + "=" + cvalue + ", " + expires + ", path=/ ;";
I've tried this with and without a path and or expiration date, but nothing seems to have an effect. What should I do?
Some extra information about my files as requested by #AndrewL64:
I made a 1 page html game. I have a index.html file, a mainstyle.css file and a main.js file for the script. In my script I use JQuery to manipulate the DOM elements. I put the code in the on page load event like this:
//==================On Page Load ===================================
$(document).ready(function () {
$("#gameContainer").hide();
$("#mainContainer").hide();
//$("#startContainer").hide();
$("#skillsContainer").hide();
prepareGame();
//startGame();
/*var cookieName = "sp_str_cookie_save1";
var saveString = "some value";
setCookie(cookieName, saveString, 10);
var cookieResult = getCookie(cookieName);*/
const cname = "someCookie";
const expires = "Thu, 2 Aug 2020 20:47:11 UTC";
const cvalue = "someValue";
document.cookie = cname + "= " + cvalue + "; " + "expires=" + expires + "; " + "path=/";
});
I found the answer in another Stackoverflow question here. In short, some browsers don't set cookies when opening a html file locally. For example Chrome doesn't, but Firefox does. So test cookies in Firefox if you are working offline.
The parameters should be separated with a semicolon and a white-space, not a comma.
Change your current code from this:
document.cookie = cname + "=" + cvalue + ", " + expires + ", path=/ ;";
To this:
document.cookie = cname + "= " + cvalue + "; " + expires + "; " + "path=/";
Check and run this JSFiddle which has the following Code Snippet and then check your browser cookies to see the new cookie added:
const cname = "someCookie";
const expires = "Thu, 2 Aug 2020 20:47:11 UTC";
const cvalue = "someValue";
document.cookie = cname + "= " + cvalue + "; " + "expires=" + expires + "; " + "path=/";
N.B. The above Code Snippet won't set the cookie since the snippet environment is just a sandbox and lacks the 'allow-same-origin' flag. Check the JSFiddle to see the above JavaScript add the cookie to your browser.

The cookie is deleted when the browser is closed

I have this cookie to store users previous selection from a menu. But I want keep this cookie stored in the browser even if the user closes the browser. This code perfectly works on IE but when I close Chrome and Firefox, the cookie getting deleted. Can anyone provide me solution for this.
function setCookie(NameOfCookie, value, expiredays) {
var ExpireDate = new Date();
document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}
function delCookie (NameOfCookie) {
if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" + "; expires=Thu, 17-Jul-24 00:00:01 GMT";
}
}
If you call the function with
setCookie('redirectcountry', 'CA')
then you set the expiry date to new Date(), that is "right now". So it's normal behavior to have the cookie be immediately deleted.
Simple solution : call it as
setCookie('redirectcountry', 'CA', true)
Did you check your browsers settings? In Firefox this is option called 'Keep until' with value 'I close Firefox' (Privacy tab).

Javascript "document.cookie" in Android?

I need help how to use correctly the javascript : "document.cookie" or
how to write cookie from javascript in Android web browser ?
I've make sure in the settings that cookie is enabled. When I checked
by using "navigator.cookieEnabled", it returns true as well.
I've a piece of javascript code as follow that has been working
everywhere
( e.g. PC browsers, iPhone ), but doesn't work in Android.
function createCookie(name) {
// cookies expired in 1 year.
var expDate = new Date();
expDate.setDate(expDate.getDate() + 365);
expDate = expDate.toGMTString();
var el = document.getElementById(name);
document.cookie = name + '=' + escape(el.value) + '; path=/ ;expires=' + expDate;
document.cookie = name + '-idx=' + escape(el.selectedIndex) + ';path=/ ; expires=' + expDate;
//alert('cookie : ' + document.cookie);
}
When I open the 'alert' comment in the last line of code, Android will
just show blank while
all other browsers show me the content of the cookie that I've just
written.
Please help.
Thanks.
I got this thing working, for Android 2.2, javascript's document.cookie works fine, just make sure that in your Webview...javascript is enabled like so:
yourWebViewVariable.getSettings().setJavaScriptEnabled(true);
for Android 3.1 just add this to your java file onLoadInit:
CookieManager.setAcceptFileSchemeCookies(true); //This is the line that specifically makes it work so the other lines is optional
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.acceptCookie();
Also, here's a few links that I found while I was trying to figure this error out, this could be helpful for others that wants to Send variables from Javascript to the Webview(Native Android Language) and Vise versa.
http://android-er.blogspot.com/2011/10/run-android-java-code-from-webpage.html
http://android-er.blogspot.com/2011/10/call-javascript-inside-webview-from.html
Thanks and Goodluck!
Ok, now I really got it (window.cookie, lol).
Just remove the space in the path definition. Seemed to work on my phone.
Edit: Put all the strings on one line too, I think it screwed up the parsing.
function createCookie(name) {
// cookies expired in 1 year.
var expDate = new Date();
expDate.setDate(expDate.getDate() + 365);
expDate = expDate.toGMTString();
var el = document.getElementById(name);
document.cookie = name + '=' + escape(el.value) + '; path=/; expires=' + expDate;
document.cookie = name + '-idx=' + escape(el.selectedIndex) + '; path=/; expires=' + expDate;
//alert('cookie : ' + document.cookie); }

Cookie created in JavaScript not updating when using ASP.NET

I am creating a cookie in JS using this:
function setCookie(name, value, expires, path, domain, secure) {
var curCookie =
name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "/") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
document.cookie = curCookie;
}
setCookie('AccountSelectedTab', '1');
when I then try to edit that cookie using ASP.NET:
Response.Cookies['AccountSelectedTab'].Value = 'some value';
It creates another cookie instead of changing it.
If I set the path to be the same on both cookies then I don't get a second one but the JS one doesn't update.
I guess I am missing something but need an idea as to what...
Thanks.
I suppose you change your code behind as :
HttpCookie cookie = new HttpCookie("newCookie");
cookie.HttpOnly = false;
without this you won't be able to access cookies through Javascript.

Categories

Resources