Reputation: 139
I have an application with a live chat feature. When it opens, the chat is in a new popup window. While this window is open, I need to prevent the user from opening another chat window (they can only have one chat going at a time). So, I have a simple flag, the following code fires when the popup loads:
localStorage.setItem('chatOpen', true);
window.onunload = function() {
localStorage.setItem('chatOpen', false);
};
And I check this flag before opening the popup. It works fine normally, but if the browser crashes, the window.onunload event does not fire, and then the user can never open the chat popup ever again. How can I remedy this?
Upvotes: 2
Views: 1288
Reputation: 50752
What if you change a logic a bit: start a timer, which update timestamp every second... and on the other side, if current time - timestamp > 1
sec, means that last page has been closed
pseudocode:
on load :
if localStorage has value with key chattimestamp and datetime.now -localstorage[chattimestamp] < 1 sec
another instance is oppened
else
settimer that every 1 sec update timestamp to localstorage[chattimestamp]
I think you can choose more than 1 second, actually 5-10 sec should be ok
Upvotes: 4