I'm trying to use local storage across various pages on the same domain, but for some reason Firefox is creating multiple instances of the same storage data across pages if they are using different ports. So if I set something for www.example.com:80
that won't persist when going to www.example.com:8000
, it will create an entirely new redundant entry of the same data. How can I rectify this and get it to use the same entry?
That's because localstorage doesn't support sharing the storage across subdomains or even domain. Thus, if you have something stored at a.example.com it won't be accessible from example.com or b.example.com.
localStorage is persistent across pages in the same domain. The normal same-origin rules are applied to DOM storage, so as long as your pages are on the same domain, the data will be accessible.
The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.
If the data to be stored is needed on multiple subdomains, local storage also does not work – because local storage is subdomain-specific. Cookies, on the other hand, are more flexible in scope – they can be written to work across multiple subdomains (or even all subdomains on the same top-level domain).
Ports must be the same for origin rules to work. The only way around this is a server-side proxy.
Definition of an origin:
Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
To pass tokens between apps, I've resorted to using cookies:
Set cookie on client side of app-001
<script>( function() { document.cookie = 'token=undefined; token_expires=Fri, 3 Aug 2020 20:47:11 UTC; path=/' } )();</script>
Then to use the cookies on the client side of app-002
<script>( function() { console.log( document.cookie.replace(/(?:(?:^|.*;s*)token*=s*([^;]*).*$)|^.*$/, '$1') ); } )();</script>
Then once you have the cookie on either app, add it to a localStorage making slightly easier access moving forward.
<script>( function() { localStorage.setItem('token', document.cookie.replace(/(?:(?:^|.*;s*)token*=s*([^;]*).*$)|^.*$/, '$1') );); } )();</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With