I have a simple little script which I am using to set a cookie:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
The problem I have this cookie is only set on one page, not across the whole domain.
How can I adjust this function so that the cookie remains across the whole domain?
To make a cookie accessible from the entire domain including any sub-domains we just add a domain parameter when setting the cookie as demonstrated in this JavaScript example.
You cannot set cookies for another domain.
If a cookie's domain attribute is not set, the cookie is only applicable to its origin domain. If a cookie's domain attribute is set, the cookie is applicable to that domain and all its subdomains; the cookie's domain must be the same as, or a parent of, the origin domain.
You can't access cookies from a different path - otherwise it would be a security hole.
You can specifiy domain ;domain=.example.com
as well as path ;path=/
("/" set cookie in whole domain)
document.cookie = cname + "=" + cvalue + "; " + expires +";path=/";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With