How should I add domain support to these functions? I want to achieve that .example.com is declared as domain, so that the cookies can be read across all subdomains of the example.com. In its current form since domain is not set, it can only be read from www.example.com
Asked
Active
Viewed 7.3k times
2 Answers
74
Here is a link on how to share cookies amongst a domain:
https://www.thoughtco.com/javascript-by-example-2037272
It involves setting the domain attribute of the cookie string like:
document.cookie = "myValue=5;path=/;domain=example.com";
This cookie should now be accessible to all sub domains of example.com like login.example.com

Rimian
- 36,864
- 16
- 117
- 117

Tom Gullen
- 61,249
- 84
- 283
- 456
-
the syntax of ppk's function seems to be different because it gets its name and expiry from its lines above: document.cookie = name+"="+value+expires+"; path=/"; what about these double quotes? – newnomad Jan 17 '11 at 12:43
-
1@newnomad: JavaScript uses quotes around string literals like most programming languages. – RoToRa Jan 17 '11 at 14:29
-
1this cant be added to cookies if I dont escape() it. but if escape - value set with path and domain – user2171669 Dec 05 '14 at 15:49
-
1I was having a similar problem, and although I was putting in a leading dot before the domain name (in order for it to be available to another subdomain), it wasn't showing until I added the path=/ portion. – Eli Oct 28 '16 at 16:42
-
2The link doesn't explain anything. – user31782 May 12 '17 at 15:01
2
In my case we needed to set a cookie that would work across our .com subdomains:
function setCrossSubdomainCookie(name, value, days) {
const assign = name + "=" + escape(value) + ";";
const d = new Date();
d.setTime(d.getTime() + (days*24*60*60*1000));
const expires = "expires="+ d.toUTCString() + ";";
const path = "path=/;";
const domain = "domain=" + (document.domain.match(/[^\.]*\.[^.]*$/)[0]) + ";";
document.cookie = assign + expires + path + domain;
}
This might not work for .co.uk etc but the principle can be used

stujo
- 2,089
- 24
- 29
-
1How would I modify this to work with .co.uk as well? Assuming it needs some regex changing – Kieran Crown May 12 '21 at 15:19