Reputation: 35
My requirements are:
Have to detect browser close event and it should not execute onpage refresh.
If code works only on browser close then have to clear localstorage.
Already i tried with onbeforeunload but it is executing on browser close event and page refresh event.
So my code only works on browser close event not on page refresh (F5 or clicking on refresh symbol).
Upvotes: 1
Views: 14168
Reputation: 1074666
You cannot tell the difference between the browser being closed and the window/tab containing your page being refreshed. The information simply isn't available.
For your specific use case, it sounds like you might be able to use session storage rather than local storage. The point of session storage is that it expires when the user is done with the page. You can try that out with this example:
display("Existing <code>sessionStorage.foo</code>: " + sessionStorage.foo);
sessionStorage.foo = new Date().toISOString();
display("New value set: " + sessionStorage.foo);
For me on Firefox, Chrome, and IE9 (so presumably IE9+), refreshing doesn't clear session storage, but closing the tab does.
Alternately, you could set a timestamp in local storage when the page is being unloaded (from onbeforeunload
), and when you come back to the page in the future, if that timestamp is sufficiently out of date, clear the storage and start fresh. That doesn't clear the store when you leave the page, but does act as though it did when you come back after an interval.
Upvotes: 8
Reputation: 20633
There is no event that gets fired when only the browser is closed. The closest is the onbeforeunload event which gets emitted when the window is about to unload its resources.
Upvotes: 0