Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting cross-subdomain cookie with javascript

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

like image 778
newnomad Avatar asked Jan 17 '11 12:01

newnomad


People also ask

Can you set a cookie for another subdomain?

Please everyone note that you can set a cookie from a subdomain on a domain. But you CAN'T set a cookie from a domain on a subdomain.

Are cookies available across subdomains?

To share cookies across subdomains, you can simply create cookies with the domain directive set to the parent domain, in this case, example.com, rather than either of the specific subdomains.

Can JavaScript set cookie for another domain?

You cannot set cookies for another domain.


2 Answers

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

like image 187
Tom Gullen Avatar answered Sep 23 '22 13:09

Tom Gullen


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

like image 28
stujo Avatar answered Sep 21 '22 13:09

stujo