I have created an angular 5 application. Which is using a token based system.Currently I am storing the token in the localstorage.I want the localstorage to be clear when the browser closes. and not clear the localstorage when the browser refreshes.The reason that I didn't use sesionstorage is because opening a page in a new tab or window will cause a new session to be initiate. How can I done this I tried with this code in app.component
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
alert("KKk")
localStorage.removeItem('authToken');
}
But it is not firing when the browser closes.What is the best method to achieve this use case. Whether using cookie storage is a good method in case of tokens
We can achieve this through the below approach.
Before Login call this function.
Here we check whether Is there any active tab present. If not cleat the localStorage and if required redirect to login(I have not done redirecting here).
To keep track of the tabs, once logged in invoke the below method.
To set inactive tab, invoke this on @HostListener
Note: This logic will not work if browser crashed or if browser closed through windows task manager.
Try with onDestroy, this gets executed when a directive, pipe or service is destroyed.
You should do that way...
Note : onBeforeUnload is executing on browser close event