But I had an idea...
What if you make a frameset, and set one of them some kind of "invisible"...
For example you give it 0 height.
And then you just have to make the ONUNLOAD event handler targeted on this frame.
On the other frame(s) you can do anything, that won't affect the window.
But if you close the window, the "invisible" frame gets UNLOADed, and runs your script.
Pretty smart and elegant... 😉
Best
Paul