I'm using the Web SQL API to store some information on a page; I'd like to save the state of the page when the user closes the page or navigates away, thus, I start with:
window.onunload = function () {
db.transaction(function (tx) {
executeSql("INSERT INTO State (foo) VALUES (?)", [foo]);
});
};
However, this is asynchronous so it doesn't complete before the page goes away.
I solve this unsatisfactorily by adding a (disingenuous, since it hasn't happened yet) alert("Saved!");
at the end of my window.onunload
, which delays the unload until the DB has a chance to do its thing, but I'd rather not have that alert if I can avoid it.
Any ideas? I need to sort of block the thread calling the onunload
function for a moment, which is what the alert does.
(BTW, to head off any suggestion that I use the synchronous openDatabaseSync
version, that API is speced and implemented only for Web Workers, not for the Window object.)