Search code examples
javascriptiossqliteexceptionmobile-safari

Invalid State Error, DOM Exception 11 in Mobile Safari calling openDatabase


I have a webapp which calls openDatabase() on init. This works fine in desktop browsers Chrome and Safari; however, when I try to open the app in Mobile Safari on iOS 4.3.3, I get an exception on the first page load:

"Error: INVALID_STATE_ERROR: DOM Exception 11"

This fails on openDatabase() inside a simple function:

       try {
            if( !window.openDatabase) {
                console.log('SQLite is not supported by this browser');
            }
            else {
                db = openDatabase('MyMobileDb', '1.0', 'MyMobileDb', 65536);
                if (doreset)
                {
                    //my drop and reset DB function
                } else
                {
                    //my init DB function
                }
            }
        }
        catch(e) {
            console.log(e);
        }

The database is not created and no further interaction with the app is possible. Other developers running earlier versions of iOS are not experiencing this issue against the same code bade. I'm also getting reports from our QA team that Android presents similar behavior. Android 3.1 works, while 2.2 and 2.1 do not.

What can I do to fix this?


Solution

  • I have some WebSQL code running in an off-line mobile app, which works in iOS 4.3.3 and desktop Safari OK.

    INVALID_STATE_ERROR: DOM Exception 11 is frustratingly opaque in that it can refer to so many different things, but I suspect the WebKit issue you link to has the answer in your case. Anyway, on to something that may help…

    FWIW in my code I initialise a database connection via a "kinda" factory, and this seems to work OK, persisting across my app (in fact, I use a database connection 'factory' plus a second prototyped object which encapsulates all my SQL, a bit like a Javascript DAO, but I'll leave that bit out for the sake of brevity).

    I've created a gist with a sample 'factory' in it (it's an extrapolation of some of my production code, so apologies for any omissions): http://gist.github.com/1044759

    This code will initialise your database connection, and create the relevant table(s) if they don't already exist.

    Here's some sample script (perhaps for $(document).ready) which will set up the db connection:

    // Initialise local db
    var mydb = new DbConnection().getDb();
    

    To use the connection, you simple call your normal transaction Javascript, using mydb as the database bit, i.e.:

    mydb.transaction(function(transaction){
      transaction.executeSql(...
    

    Hope that helps.