Reputation: 21162
From my (poor) understanding of the Web Storage, the sessionStorage
object is maintained per-tab, it survives page reloads and page navigation, and it gets destroyed on tab close or browser process termination.
Is there a way to listen to the sessionStorage
destroy event?
I need to perform an HTTP call when the tab or window is being closed and it seems the sessionStorage
is the single object which follow a similar lifecycle.
Upvotes: 2
Views: 1087
Reputation: 1075427
Is there a way to listen to the sessionStorage destroy event?
No, there is no "destroy" event for session storage.
I need to perform an HTTP call when the tab or window is being closed and it seems the sessionStorage is the single object which follow a similar lifecycle.
You can't differentiate between page reload and navigating away from the page.
The only thing I can think of to get close to what you want to do is to do this:
beforeunload
or unload
, use sendBeacon
to do your HTTP call (it has to be a POST). You can't just use standard ajax (XMLHttpRequest
/fetch
), browsers are actively disabling standard ajax in unload events. So use sendBeacon
if it's there, falling back to a standard (and — ugh! — synchronous) ajax request if it isn't (as that suggests and older browser were it may still work).sessionStorage
for a marker and:
You'll need to be sure that the server handles the possibility that, because of the vagaries of network requests (particularly as beacons are always asynchronous), the two requests may be received by the server out of order. So include some serialization information in them (for instance, a value from performance.now()
, falling back to Date.now()
if necessary).
Or, of course, use polling when the page is open and a timeout to indicate the user has left the page. The tradeoffs between the approaches will be fun to weigh. :-)
The user window.document (interesting username!) points out that you may be able to use web sockets for this. I don't have much experience using web sockets (must fix that!) but I think the general idea is that you'll see a socket disconnect when the user leaves the page or refreshes, but (like the above) if it's a refresh, you'll see a socket connection again very soon thereafter — which is like the "never mind!" call above.
Upvotes: 3