document.cookie not working - javascript

I am trying to use document.cookie in javascript in an alert(for an experimental purpose). Initially, it was displaying the cookie's fine, all of sudden its displaying "style_cookie=null".
I was doing this in phpbb3. I am trying to add a custom page inside it and I am in the process of building it. So the cookie setter is phpbb3.
I am not sure whats going wrong here? Is it related to cookie time-out or cookie expiration? I am confused, some help would be appreciated.
The code looks like the following,
alert(document.cookie);
Thanks,
Abi

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!

It can be caused by several things:
cookie expiration (if you don't set the expiration, the cookie is per session)
http only - you can tell browser not to send the cookie value
cookie scope - cookie can be valid for some subdomains or subURLs only
Note that if you want to list all cookies, you can use another tools. For example, in Firefox, you can right click -> View Page Info -> Security -> View Cookies.

have you test your script over http or just call a HTML file? cookie send over http, so you must call it inside web server like (http://localhost/test_cookie.html)

the following two functions are safe to use to set or get a cookie and tested also
function setCookie(c_name, value, exdays)
{
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;
}
function getCookie(c_name)
{
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++)
{
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name)
{
return unescape(y);
}
}
}
for more information visit this page in W3Schools

Related

Cookie collision: is it possible to distinguish between parent domain and subdomain cookies in Django and Javascript?

I have built a bunch of Django websites at a single domain:
example.com
site1.example.com
site2.example.com
site3.example.com
They are supposed to be completely independent — used by different people for different purposes.
However cookies set by example.com are given priority by Django, and values set by site1.example.com, site2.example.com etc. are ignored if the parent domain has set a cookie with the same name.
How it works:
When the first page is loaded, it sets a cookie so the server knows to send a computer page or a mobile page with the next request.
The Django program builds the correct version based on the cookie value.
When site1.example.com loads, it sets a cookie asking for the mobile version. But then the Django program sees the value set by example.com and ignores the correct cookie.
So, I need a way to do one of the following:
prevent site1.example.com from reading the cookie of example.com
differentiate in Django the domain associated with the cookie so I can tell that the value is wrong
find a way to set a parent domain cookie in Javascript that makes it inaccessible to subdomains (I'm not using www)
If I can't find an elegant solution, I will likely end up changing the cookie name to vary with the domain name.
I know that I could use the session framework, but apart from this particular issue, everything works great. I would really like to avoid modifying my existing system, though obviously I will if I have to.
[update] Here is the cookie-setting function:
function setCookie(cname, cvalue, exdays) {
var domain = window.location.hostname;
if (exdays > 7) exdays = 7; // max in Safari
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var name = cname + '=' + cvalue + '; ';
var expy = 'expires=' + d.toUTCString(); + '; ';
var domn = '; domain=' + domain + '; ';
var path = 'path=/; ';
var secu = 'samesite=lax; secure;';
var complete = name + expy + domn + path + secu;
document.cookie = complete;
}
Since you say the websites are supposed to be completely independent the 3rd solution you propose seems most sensible. You should not be setting cookies in such a way that they are accessible by subdomains. Currently you are specifying the domain in the cookie, you should be skipping the domain which would mean the cookie would only be sent for the current domain (At least in modern browsers, IE does not follow this specification). If a domain is specified in the cookie it means that the cookie would also be used for the subdomains.
As mentioned in RFC 6265 - section 4.1.2.3:
If the server omits the Domain attribute, the user agent will return
the cookie only to the origin server.
Hence your cookie setting function should be like the following:
function setCookie(cname, cvalue, exdays) {
// Domain should not be set unless cookie needs to be accessed by subdomains
// var domain = window.location.hostname;
if (exdays > 7) exdays = 7; // max in Safari
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var name = cname + '=' + cvalue + '; ';
var expy = 'expires=' + d.toUTCString(); + '; ';
// Domain should not be set unless cookie needs to be accessed by subdomains
// var domn = '; domain=' + domain + '; ';
var path = 'path=/; ';
var secu = 'samesite=lax; secure;';
var complete = name + expy + path + secu;
document.cookie = complete;
}
As a temporary fix, I added some code to my setCookie function:
var domain = window.location.hostname;
deleteParentCookieIfNecessary(name, domain);
deleteParentCookieIfNecessary contains:
function deleteParentCookieIfNecessary(name, domain){
var parts = domain.split('.');
if (parts.length > 2){ // on subdomain
var domain = parts.slice(-2).join('.');
document.cookie = cname + '=;domain=.' + domain + ';path=/;max-age=0';
}
}
The result is that when the cookie is set, if the url is a subdomain then the parent-domain's cookie of the same name will be automatically deleted.

JEE Servlet / JS: document.cookie not returning same thing between Chrome and IE

I have a problem getting a cookie value from my response in IE. On Chrome, everything works fine, I have a token which is named fileDownloadToken and I set it in my Java controller like this:
String tokenValue = value;
response.addCookie(new Cookie("fileDownloadToken",tokenValue);
With my JS I get it with just a:
var cookieList = document.cookie;
And then I split it to search for the cookie I want.
The problem comes with IE, I can see that it is in my response header :
But when I do a console.log(document.cookie), I can't see it. So obviously it's not a problem of HttpOnly because otherwise I wouldn't be able to see it in Chrome. I've also tried setting the cookie in server side using:
final StringBuilder cookie =
new StringBuilder("fileDownloadToken=" + new StringBuilder(tokenValue) + "; ");
response.addHeader("Set-Cookie", cookie.toString());
But It doesn't work either for IE (works for Chrome too though).
I really have no idea what to try now. Thanks in advance.
EDIT: I have in my JS a function that regularly check for the cookies:
var fileDownloadCheckTimer;
function checkDownloadToken() {
fileDownloadCheckTimer = window.setInterval(function() {
var cookieValue = getCookie("fileDownloadToken")
if (cookieValue == token)
clearTimer();
}, 2000);
};
To whom it may concern, I solved the problem with just adding
cookie.addPath("/");
Cheers

Javascript - cookies, is there a way to write a cookie for all browser at once?

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.

document.cookie is still accessible on IE11, even though cookies are disabled

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.

Bookmarklet for set and read cookies

I need (for practice) to set a cookie via bookmarklet in website X, and read him with another bookmarklet from website Y.
For example, set a cookie named "user" with value of "Guy" in Google, and read this from YouTube.
I managed to set the cookie, but can't think of any idea how to read him from website b.
Thanks!
You need two bookmarklets, a getter and a setter.
You go to site X and use the getter bookmarklet to read the cookie and let the user copy it to his clipboard.
Then you go to site Y and use the setter. The setter will prompt the user for the bookmarklet and the user will then paste it into the prompt. The code will then set the cookie accordingly.
You can of course combine these two bookmarklets into a single getter/setter. The prompt will contain the current cookie for the page. The user can then choose to either copy the cookie and cancel (using it as a getter) or choose to to alter the cookie and click "OK" (using it as a setter).
I was looking for a way to share cookies of a specific website with a friend (reading them in my browser via bookmarklet and my friend setting them on his browser also via bookmarklet). Not quite what you asked for, but searching brought me here. This is my approach:
First there is a bookmarklet for exporting cookies. It will remove unnecessary white-spaces and encode your data in a base64 string for safe transport:
javascript:(
function(){
prompt("GET cookies encoded in base64", btoa(document.cookie.replace(/\s/ig, "")));
}
)
();
Then there is a second bookmarklet for importing all cookies encoded in the string. You can also set an optional lifetime here (thanks to https://www.quirksmode.org/js/cookies.html):
javascript:(
function(){
var inputstring = prompt("SET cookies decoded from base64");
var inputclean = atob(inputstring).replace(/\s/ig, "");
if (confirm("These cookies will be imported:\n\n" + inputclean.replace(/;/ig, "; "))) {
var days = prompt("Cookie lifetime in full days", "365");
var cookiearray = inputclean.split(";");
cookiearray.forEach(function(entry) {
var expires = "";
var split = entry.split("=");
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = split[0] + "=" + (split[1] || "") + expires + "; path=/";
});
}
}
)
();
Do not forget you have to run those on a specific website or tab. It does NOT export the entire collection of the cookies your browser is storing.
According to this StackOverflow, how to get cookies from a different domain with php and javascript you can't get cookies from another domain UNLESS you have access to it, as it would be a huge security flaw.

Categories