How to execute a javascript after a session is closed?

Hi, I use a javascript to ask if you’re sure to close the browser tab.

I need to detach the listener if the session expires or other error occurs.

How to trigger the javascript on this situations?