My accomplice and I ran into an issue with using an iPad to view a site we develop. The page in question saves up some data, and posts it to the server after certain events take place. This batch of data needs to be sent when they suddenly click the back button. Obviously iPad doesn't really want you to do that. It doesn't let you handle "beforeunload" events.
I came up with a hacky idea of using a hash change event to do our dirty work. Here's the example code:
DISCLAIMER: This isn't suitable for mission critical applications. Don't use it. Also, all error handling code has been pretty much omitted from this snippet. If you choose to use it, be smart and take the time to handle any errors you can.
function setupHash() {
var url = window.location.toString();
if (url.indexOf('#busy') == -1) {
window.location = url + '#busy';
}
$(window).hashchange(function() {
if (!window.location.hash) {
myCustomModule.SendData(function () {
history.go(-1);
});
return;
}
});
};
When the user lands on the page with their iPad, it checks to see if the window location is on a hash of "busy". This is our trick to make the browser push another entry into its history. Think of it this way, the history has something like this: ["PageA", "PageB", "PageB#busy"]. If you're on "PageB#busy", hitting back takes you to "PageB".
When you click back, and a hash changed event is triggered, we'll see that there's no hash avaialble. That's our signal to do our dirty work. In this case, myCustomModule.SendData(...) is being passed a callback function. We're performing an ajax post, and the callback gets invoked after it's done. The callback contains history.go(-1);. When that callback executes, it'll take the user back to "PageA" (which is what they probably expected to happen anyway).
Because it's evil and doesn't account for a lot of possibilities. For one, what if the user just types in a new address and hits go? There's no hash change for that. All of the data is lost. I suspect something like HTML5 local storage could help with this by picking up on it with the next page visit (I don't know much about local storage, just a hunch).
What if using the hash causes complications with other url-bound data? Or another hash? Then you have to program yourself out of a corner.
What if the user refreshes the page? "Just tell them not to do that."
In short, this method probably won't be the endgame for solving this problem. I'm sure it will evolve into something more fool proof, and less hacky. In time, I suppose.