Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sessionStorage cleaned up unexpectedly on Android

I have a website which saves a stringified JavaScript object into the sessionStorage. It works well on desktop browsers - data survives over page reloads as per described on MDN.

On Android phones, it is not uncommon that a tab is reloaded when user switches back from another tab or when the browser is brought back from background to foreground, and I expect the sessionStorage will persist. This doesn't however seem to be the case. The sessionStorage is gone missing, as if a new session is created.

I have thought of using localStorage instead, which will not expire even if the session is closed. It doesn't really sort out all my problems though - as I expect a user can open it multiple times on multiple tabs, and do different things on each of them.

So my questions are:

  1. Is the sessionStorage behavior described above as expected? If not, what can I do to rectify it?
  2. If the behavior is as expected, and I have to rely on localStorage, how can I identify the object stored for each individual tab?

Thanks in advance for your help!

like image 829
CLDev Avatar asked Apr 16 '16 02:04

CLDev


1 Answers

As others commented, SessionStorage is temporary by design. Mobile browser lifecycle is highly geared towards reducing resource usage and tabs are teardown more aggressively.

To workaround this issue, you can push a random tab ID to the URL and then prefix all LocalStorage keys with this ID. When tab is refreshed you simply read the tab ID from the URL and use it for accessing data in LocalStorage.

LocalStorage has a very simple API, so you could write a wrapper hiding the key prefixing away from your other code.

like image 181
v3nom Avatar answered Nov 14 '22 23:11

v3nom