W3C home > Mailing lists > Public > whatwg@whatwg.org > May 2012

[whatwg] Declarative unload data

From: Tab Atkins Jr. <jackalmage@gmail.com>
Date: Mon, 7 May 2012 09:53:07 +0200
Message-ID: <CAAWBYDDO8GD7qpsbETCKi17GXVO_nFd7HdF=N=44sBm0A6zieA@mail.gmail.com>
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
Received on Monday, 7 May 2012 00:53:07 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Wednesday, 30 January 2013 18:48:08 GMT