Search code examples
javascriptsqlhtmlonunload

Save state using HTML5 Web SQL on window unload


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.)


Solution

  • I'll just mention for posterity that another idea I've come across is to open a modal dialog with a timeout, like this:

    window.showModalDialog('javascript:document.writeln ("<script>window.setTimeout(function () { window.close(); }, 100);</script>")');
    

    But that's not completely cross-platform, perhaps. And the dialog window is visible in some browsers (Safari at least).