Link to home
Start Free TrialLog in
Avatar of bharath kuamr Reddy
bharath kuamr Reddy

asked on

In Angular js How can i clear LocalStorage values when browser closed not browser tab closed.

Hi Sir,

In my Angular Application i used local storage. when i logged in the app then i closed the browser with out logoff.Then i again i open the browser  with my app URL.it is showing prev. logged in section only.i want when i closed the browser cross mark then it need to be clear . not closed when  i closed Browser tab.
Avatar of Kanti Prasad
Kanti Prasad

Hi

Try
localStorage.removeItem(key);
Avatar of bharath kuamr Reddy

ASKER

where i need to call that one.because in browser close event or in tab close event
Hi

You can make use of the beforeunload event in JavaScript.

window.onbeforeunload = function() {
  localStorage.removeItem(key);
  return '';
};
But That above method will work work when browser closed event and tab closed tab as well.But my point is when i closed tab my local storage value i did not want to clear.only when i close browser close then it need to work like gmail
ASKER CERTIFIED SOLUTION
Avatar of Kanti Prasad
Kanti Prasad

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alexandre Simões
I think you're addressing the issue in the wrong way.
You cannot rely on the window events to do this because if the browser crashes, or whatever happens that makes those events no to be triggered, you'll end up with the same problem.

What you need to do is to be able to identify that the application is starting, and if the localCache is present, discard/refresh it.
You're even using AngularJS, so if you have a Single-Page App, whenever the Angular app loads you can clean the LocalStorage. Just note that this will also happen if the user does Ctrl+F5.
$(window).unload(function(){
 localStorage.removeItem(key);
});

above one working fine.from my site i am navigating to other site then click back button Then my local storage is clearing but that is not happend.when i am click back to my site that logged in need to stay.