Sometimes you’re just an honest guy trying to script

JavaScript May 27th, 2009 @ 18:05

Today, I ran into some JavaScript security issues that cost me a few hours too many of my life.

I wanted to show the user a confirmation message when closing a pop-up (OK I know, but sometimes you just got to use them!) to make sure he doesn’t lose any data when leaving.

But we can do this! Right…?

This isn’t really any big issue, as the onBeforeUnload event can be used for these exact scenarios, with a nice message too:

window.onbeforeunload = function (event) {
    // message to display (in between the standard message provided by the browser)
    return "Leaving now will have you lose everything."
};

The special case here was that I had a SWF running in the window, which needs to be unloaded (close its connections etc) when closing the browser window. That has to be done in the onBeforeUnload event as well, since it’s too late when we’re at onUnload.
The problem is that there’s no way of knowing what the user answered to the question arisen from onBeforeUnload, other than finding out when the event’s traveled onwards to the onUnload event. By which time it is too late.

So I ended up in a situation where everything was fine if the user decided to keep the browser window open (“Cancel” in the confirmation box), but should he close the window – which is fine too – I had no way of closing the connections etc in the SWF.

But why?

The reason to this is of course a security matter. Some clever fellas have set some restrictions to what you can do with Javascript to avoid misuse, for example extreme annoyance with pop-up ads or such. There’s nothing wrong with that.
But sometimes you just want to yell to JavaScript’s mom and tell her that I’m a perfectly honest guy trying to make the world better for my users! :)

What would’ve helped me

So what do I want, then? Well, it would’ve been nice if I could’ve gotten an answer from the confirmation box rendered with my custom message (“OK, leaving now…”).
It’s perfectly fine that the unload event cannot be stopped once the user’s said “OK, close”. But at least I would’ve wanted the chance to act upon the user’s choice before the document was unloaded.

So my final solution was just to warn the user that everything was hitting the fan, and at the same point notify my SWF that it was to be unloaded etc. It’s an OK solution, but not perfect from a usability perspective…

End of rant.