[whatwg] Declarative unload data
Tab Atkins Jr.
jackalmage at gmail.com
Mon May 7 00:53:07 PDT 2012
Besides those annoying "Are you sure you want to leave this page?"
dialogs, the primary use of the unload events is a final, desperate
attempt to throw a message at the server, either to save some data or
release some server-held resource. However, this is tricky to do
reliably, because browsers kill pending XHRs as they unload the page.
Right now, I think the most reliable method is to create an <img> and
set its @src, because of an old quirk in IE that other browsers have
copied which means that pending image loads are carried to completion
rather than being killed. This is, obviously, stupid. (Another,
stupider, method is to prevent the handler from exiting by spinning a
no-op loop for several seconds, as I think browsers won't unload the
page until the handler exits?)
Can we fix this? In a thread over on corp G+, we had a short
discussion about this, which concluded with a proposal for an API
something like:
var foo = new unloadHandler('http://example.com/ajax');
foo.data = "bar"
/* Now, if the page ever gets unloaded, you're guaranteed that
"http://example.com/ajax" will eventually get a request with the value
"bar". */
Presumably you'd be able to set other relevant XHR properties, like
un/pw and get/post and such, on the unloadhandler object.
A page can set up an unloadHandler immediately on loading, and just
keep its .data property updated over time. The author is then secure
in the knowledge that, barring complete computer destruction, if the
user shuts down their browser the server will receive a message with
whatever .data held at the time.
The benefits of this over traditional unload events are:
1. The author doesn't have to use fiddly hacks to avoid their request
getting killed as the page unloads.
2. The browser can go ahead and kill the page immediately, and send
the request at its leisure.
3. This approach is even friendly to things like power-loss, where
unload events are useless, as it can keep the appropriate data in
non-volatile storage and then send the data the next time the browser
starts. (This is obviously not great for some use-cases, like
tracking user's session length or something, so maybe this is
controllable?)
Thoughts?
(hat-tip to Ojan, who came up with the API proposal, and several other
Googlers in the thread)
~TJ
More information about the whatwg
mailing list