use localStorage across subdomains

This is how I use it across domains...

  • Use an iframe from your parent domain - say parent.example
  • Then on each child.example domain, just do a postMessage to your parent.example iframe
  • All you need to do is setup a protocol of how to interpret your postMessage messages to talk to the parent.example iframe.

I suggest making site.example redirect to www.site.example for both consistency and for avoiding issues like this.

Also, consider using a cross-browser solution like PersistJS that can use each browser native storage.


Set to cookie in the main domain:

document.cookie = "key=value;domain=.mydomain.example"

and then take the data from any main domain or sub domain and set it on the localStorage


If you're using the iframe and postMessage solution just for this particular problem, I think it might be less work (both code-wise and computation-wise) to just store the data in a subdomain-less cookie and, if it's not already in localStorage on load, grab it from the cookie.

Pros:

  • Doesn't need the extra iframe and postMessage set up.

Cons:

  • Will make the data available across all subdomains (not just www) so if you don't trust all the subdomains it may not work for you.
  • Will send the data to the server on each request. Not great, but depending on your scenario, maybe still less work than the iframe/postMessage solution.
  • If you're doing this, why not just use the cookies directly? Depends on your context.
  • 4K max cookie size, total across all cookies for the domain (Thanks to Blake for pointing this out in comments)

I agree with other commenters though, this seems like it should be a specifiable option for localStorage so work-arounds aren't required.