Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local storage across pages on same domain but using different ports

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?

like image 588
Joey Avatar asked Mar 14 '14 20:03

Joey


People also ask

Does localStorage work across domains?

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.

Does local storage persist across pages?

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.

Is local storage available across tabs?

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.

Does local storage persist across subdomains?

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


2 Answers

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

like image 115
Diodeus - James MacFarlane Avatar answered Oct 05 '22 22:10

Diodeus - James MacFarlane


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>
like image 38
Jack Robson Avatar answered Oct 06 '22 00:10

Jack Robson