0

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"?

Junho Ahn
  • 36
  • 5
  • 2
    I don't think so, the distinction is irrelevant as far as your website should be concerned. It's not even reliable anyway; if you force-quit the browser or it crashes, the event won't fire either. Think of some other way to achieve whatever you want to achieve without relying on detecting a browser-close. – deceze Aug 31 '21 at 06:35
  • Why don't save `onload` and `onchange` the size of window? You will always have the updated data. – Simone Rossaini Aug 31 '21 at 06:36
  • deceze // thanks, I couldn't think about undetectable events. now I need to find new way – Junho Ahn Aug 31 '21 at 06:40
  • Simone // I think I cannot use the size values even if I save it. I couldn't get size value from `event` of `unload` and `beforeunload`. they were `undefined`. so I cannot compare using it – Junho Ahn Aug 31 '21 at 06:42

1 Answers1

2

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.

geisterfurz007
  • 5,292
  • 5
  • 33
  • 54