Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cookie (with JS) for whole domain not specific page

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?

like image 575
Sheixt Avatar asked Sep 24 '14 15:09

Sheixt


People also ask

How do you set a cookie in 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.

Can JavaScript set cookie for another domain?

You cannot set cookies for another domain.

Are cookies domain specific?

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.

Can I set cookie for another path?

You can't access cookies from a different path - otherwise it would be a security hole.


1 Answers

You can specifiy domain ;domain=.example.com as well as path ;path=/ ("/" set cookie in whole domain)

document.cookie = cname + "=" + cvalue + "; " + expires +";path=/";
like image 103
Wojciech Mleczek Avatar answered Sep 23 '22 06:09

Wojciech Mleczek