Reputation: 46
I need to make a cookie when specific event has been heard. (click for example)
and delete the cookie when the user closes the browser. if the user closes only tab, cookie should not be deleted.
I have tried beforeunload
and unload
to check window size after the tab is closed.
but it didn't work. I think those events don't have any attribute about window size.
any way to detect "browser close"?
Upvotes: 0
Views: 948
Reputation: 5874
This is not an answer to the question in the title but solves the problem at hand (deleting a cookie on browser close) possibly in the most reliable way.
Use a session cookie!
They are deleted as the last browser window is closed. From MDN on document.cookie:
If neither expires nor max-age specified it will expire at the end of session.
Now what does "end of session" mean? This answer holds the... answer:
the cookie will then expire at the end of session (ie, when you close the browser)
There seem to have been some differences between browsers 5 years ago following this answer, however I am unsure about the current status of that. Depending on your usecase, this is still likely to suffice.
Detecting the browser closing through a JS event would be very unreliable due to conerns raised in @deceze's comment:
if you force-quit the browser or it crashes, the event won't fire either
Further than that, I don't think (although I don't have proof from any docs) that there is a respective DOM event for that to occur.
Upvotes: 2