Re: [whatwg] beforepopstate event?

On Fri, 27 Jan 2012, Thomas Broyer wrote:
> 
> A common use case for beforeunload is to prompt the user before leaving 
> when it has unsaved changes. For instance, you edited a mail draft, 
> updated the phone number of a contact, or filled any kind of form, but 
> you didn't save your changes; when you "navigate away", beforeunload can 
> be used to prompt you whether you really want to go (and lose your 
> changes).
> 
> Within a "single-page app", where you use location.hash=xxx and
> hashchange, or pushState() and popstate, to handle the navigation,
> there doesn't seem to be any way to prompt the user and possibly
> *cancel* the navigation. Something like:
> 1. you're looking at your mail inbox, and click on "new mail"
> 2. you type in some text
> 3. you click on the "previous page" button of your browser, or trigger
> an equivalent action using a keyboard shortcut (possibly mistakenly)
> As the app developer, I'd like to be able to prompt the user whether
> he really want to go (and lose his changes), and if he actually wants
> to continue editing his mail draft (and/or save it before navigating
> again), then *cancel* the "history traversal"; in a similar way as if
> I developed a "multi-page app" (or if he'd close the window/tab or
> navigate away from the app): I could then do that using the
> beforeunload event, either cancelling it or setting its returnValue to
> some non-empty string value.

Ah, yeah. This isn't supported. I would recommend just making the app not
discard the state, so it becomes a non-issue. They hit back, and the 
message is saved to drafts and can be obtained again by going forward. You 
can put up a message saying that the draft will be discarded in five 
minutes or some such, if the ideal model is for the data to be lost.

The reason onbeforeunload makes sense is that there's no way to do 
anything once the page is unloaded. But that doesn't apply here, where the 
same code is still running.


> Unless I missed something, all I can do is to handle the hashchange or
> popstate event and use Window.confirm() or similar, and only update
> the page from the location.hash or history.state if he confirms; but
> then navigation has already taken place, I cannot cancel the
> navigation but only "ignore" it.

Well, you can always just do history.forward() or whatever, to go back to 
the previous state. :-)

-- 
Ian Hickson               U+1047E                )\._.,--....,'``.    fL
http://ln.hixie.ch/       U+263A                /,   _.. \   _\  ;`._ ,.
Things that are impossible just take longer.   `._.-(,_..'--(,_..'`-.;.'

Received on Wednesday, 6 June 2012 23:45:40 UTC