Search code examples
htmllocal-storageoffline-caching

HTML5 Offline storage not working


This is the code provided by the W3C example for offline web storage : http://www.w3.org/TR/offline-webapps/

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" charset="utf-8">
        function renderNote(row) {
          console.log(row);
        }
        function reportError(source, message) {
          console.log("err");
        }

        function renderNotes() {
          db.transaction(function(tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)', 
              []);
            tx.executeSql('SELECT * FROM Notes', [], function(tx, rs) {
              for(var i = 0; i < rs.rows.length; i++) {
                renderNote(rs.rows[i]);
              }
            });
          });
        }

        function insertNote(title, text) {
          db.transaction(function(tx) {
            tx.executeSql('INSERT INTO Notes VALUES(?, ?)', [ title, text ],
              function(tx, rs) {
                // …
              },
              function(tx, error) {
                reportError('sql', error.message);
              });
          });
        }
    </script>
  </head>
  <body>
  </body>
</html>

There is no console log output at all. What is the matter?


Solution

  • The instantiation of the db and execution of the function was missing.

    Check this JSfiddle: http://jsfiddle.net/Ax5d7/4/

    JavaScript

    var db = openDatabase("notes", "", "The Example Notes App!", 1048576);
    
    function renderNote(row) {
        console.log(row);
    }
    
    function reportError(source, message) {
        console.log("err");
    }
    
    function renderNotes() {
        db.transaction(function(tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)', 
            []);
    
            tx.executeSql('SELECT * FROM Notes', [], function(tx, rs) {
                for(var i = 0; i < rs.rows.length; i++) {
                    renderNote(rs.rows[i]);
                }
            });
        });
    }
    
    function insertNote(title, text) {
        db.transaction(function(tx) {
            tx.executeSql('INSERT INTO Notes VALUES(?, ?)', [ title, text ],
            function(tx, rs) {
                // …
            },
            function(tx, error) {
                reportError('sql', error.message);
            });
        });
    }
    
    renderNotes();
    

    Even more simplistic

    var db = openDatabase("notes", "", "The Example Notes App!", 10000);
    
    db.transaction(function(t) {
        //t.executeSql("DROP TABLE Notes");
        t.executeSql("CREATE TABLE IF NOT EXISTS Notes(title TEXT, body TEXT)");
        t.executeSql("INSERT INTO Notes VALUES(?, ?)", [ 'title', 'content' ]);
    });