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.