use localStorage across subdomains
I'm replacing cookies with localStorage on browsers that can support it (anyone but IE). The problem is site.com and www.site.com store their own separate localStorage objects. I believe www is considered a subdomain (a stupid decision if you ask me). If a user was originally on site.com and decides to type in www.site.com on her next visit, all her personal data will be inaccessible. How do I get all my "subdomains" to share the same localStorage as the main domain?
This is how I use it across domains...
- Use an iframe from your parent domain - say parent.com
- Then on each child.com domain, just do a postMessage to your parent.com iframe
- All you need to do is setup a protocol of how to interpret your postMessage messages to talk to the parent.com iframe.
I hope it helps :)
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.
I suggest making site.com redirect to www.site.com 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.com"
and then take the data from any main domain or sub domain and set it on the localStorage