use localStorage across subdomains

2019-01-02 17:58发布

问题:

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?

回答1:

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 :)



回答2:

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.



回答3:

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.



回答4:

I'm using xdLocalStorage, this is a lightweight js library which implements LocalStorage interface and support cross domain storage by using iframe post message communication.( angularJS support )

https://github.com/ofirdagan/cross-domain-local-storage



回答5:

This is how I solved it for my website. I redirected all the pages without www to www.site.com. This way, it will always take localstorage of www.site.com

Add the following to your .htacess, (create one if you already don't have it) in root directory

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]


回答6:

You can just use the document.domain property. If you put this in the first actions of JavaScript:

document.domain="mysite.com";


标签: