0

I'm using this code to delete data when the user close the window

window.onbeforeunload = function() {
    localStorage.clear();
};

And it's working fine, but I've just realize that this method is deleting data after refreshing the page with 'F5' also. Is there another way to delete data only when the user close the window or tab?

What am I trying to do?

I should not use cookies. I need to persist my session over the tabs in any navigator, but:

  • When the user close window the data has to be deleted
  • When the user press 'F5' key the data shouldn't be deleted

Why am I not using sessionStorage?

Because when you are already signed on my website and suddenly you open another tab with the same direction my website should alert the user that he has an active session.

napstercake
  • 1,815
  • 6
  • 32
  • 57
  • You try all the solutions here ?http://stackoverflow.com/questions/21227383/how-to-detect-browser-window-tab-close-event – OriEng Mar 14 '17 at 16:56
  • hi @OriEng I've been there before without any luck :( – napstercake Mar 14 '17 at 20:30
  • May be you need sessionStorage? You may alert a user with setting a cookie, and if another tabs receives such a cookie, you can warn him/her. – Eugene Lisitsky Mar 14 '17 at 20:44
  • Save a date there, and check for it being somewhat same... No way to do it "properly" as it would mean insecurity to user – Akxe Mar 14 '17 at 20:44
  • Or actually use both session and local storage, and if not local neither session are set, then the user is new, otherwise it is refresh or new tab... Or try something yourself, you get the gist, and then share the answer – Akxe Mar 14 '17 at 20:46
  • @Akxe but it's the same, if I use local storage like a "key indicator" i'll have the necessity to delete the data and the way to do it its using the code that it's deleting my data even if I refresh the page. – napstercake Mar 14 '17 at 20:56
  • @EugeneLisitsky maybe it's probably the only solution. – napstercake Mar 14 '17 at 20:58
  • how about [this](http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch) and [that](http://stackoverflow.com/questions/11183682/how-to-prevent-are-you-sure-you-want-to-navigate-away-from-this-page-alert-on) ? – Jeb50 Mar 14 '17 at 21:17

1 Answers1

-1

This will work:

$(document).ready(function()
{
    $(window).bind("beforeunload", function() {
        localStorage['var_name'] = "";
    });
});
Henry Lynx
  • 1,099
  • 1
  • 19
  • 41
  • This is just the jQuery equivalent of the plain JS that the OP provided in the question, and said it doesn't do what he wants, because it's also triggered on refresh. – Elezar Nov 26 '19 at 00:28