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.
Related
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.
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.
I have a page with a hidden form where a value is echoed by php.
With javascript/jQuery I pick up the value and store it in a cookie. The user is redirected to an external page, then is redirected back to my site on a different page. On this page the cookie value is "0" (the value is lost).
Update: The last page is in a directory above the page where the cookie is set. I set the "path" on the cookie but it still doesn't work.
So - first I do the redirect (by submitting a form) , then I set the cookie:
function sendPostRequest(){
var $ = jQuery;
document.myform.submit(); //submitting the form
var now = new Date();
var time = now.getTime();
time += 144000 * 1000;
now.setTime(time);
document.cookie =
'member_id=' + $('#member_input').val() + //getting the value, setting the cookie
'; expires=' + now.toUTCString() +
'; path=http://domain-name/the-last-page/';
console.log(document.cookie); //the cookie is set
alert($('#member_input').val());
}
The cookie is set as it should after the redirect.
When the user comes back from the external page to the new page , it shows member_id=0 . So the value is lost.
I suspect something is wrong with the "path". I have tried path=/before. The initial page has a path like: http://domain-name/directory/the-first-page/ .
Update 2:
Another info that may be relevant is that the intial page is not SSL-encrypted, but the external page is SSL-encrypted, and the final page isn't.
var d = new Date();
var days=5;
d.setTime(d.getTime() + (days*24*60*60*1000));
var expires = ""+d.toUTCString();
document.cookie =
'member_id=' + $('#member_input').val() + //getting the value, setting the cookie
'; expires=' + expires +
'; path=/';
use date to set the expiry of the cookie and use this formula to set number of day for the expiry
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=/";
I have an app that is run from a compiled DLL on a web server. I need to do some Single Sign On (SSO) integration with the app, and the only way I can "inject" functionality, is to modify an external JavaScript file that gets referenced.
In the JavaScript file are some code blocks to set cookies with the session ID of that App. I tried adding more code to add more cookies so I could read the cookies from another sub domain, but the cookies don't get set!
I call the exact same cookie set function with a different name and it doesn't work. I debugged with FireFox and watched the JavaScript code get called for my new cookies, but still, no new cookies!!! I even see the existing cookies being updated!!! What gives!
Can anyone save my sanity!?!?!?
Here is the cookie setting function:
function setCookie (name,value,expires,path,domain,secure)
{
document.cookie = name + "=" + escape (value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
And here is the code that calls it:
var twoHours = 1800*1000;
var expDate = new Date();
var secondExpire = expDate.getTime();
expDate.setTime(expDate.getTime() + twoHours);
setCookie("mysession",123456789,expDate,"/",null,false);
setCookie("mylastConnect",secondExpire,expDate,"/",null,false);
Try setting the domain to ".exemple.com". This should make the cookie accessible for all subdomains of exemple.com (but not to http://exemple.com, you'd have to put a second cookie).
Also check your browser's cookie settings, but I assume you've done that.