block by nitaku 6890861

IndexedDB

Full Screen

A test of the Indexed Database API. It simply records and displays when the user has already visited the page.

The code illustrates the creation of the schema, the definition of an auto-increment key, the use of a transaction to write to and read from the DB. Date formatting is done by using the Moment.js library.

If you want to delete the database from your browser, follow this guide (Chrome).

References: the W3C specification, an article on HTML5 rocks.

index.js

(function() {

  window.main = function() {
    /* the value '2' as DB version makes me laugh, but is the only way I can make it work...
    */
    var request;
    request = indexedDB.open('openlog', 2);
    request.onupgradeneeded = function() {
      /* called whenever the DB changes version. triggers when the DB is created
      */
      var db, store;
      db = request.result;
      store = db.createObjectStore('timestamps', {
        keyPath: 'id',
        autoIncrement: true
      });
      return console.log('Database created or upgraded.');
    };
    return request.onsuccess = function() {
      /* called when the connection with the DB is opened successfully
      */
      var cursorRequest, db, keyRange, now, store, tx;
      db = request.result;
      console.log('Database connection opened.');
      /* open a transaction
      */
      tx = db.transaction('timestamps', 'readwrite');
      store = tx.objectStore('timestamps');
      /* store a new record with the current timestamp
      */
      now = new Date();
      store.put({
        t: now
      });
      /* get everything in the store
      */
      keyRange = IDBKeyRange.lowerBound(0);
      cursorRequest = store.openCursor(keyRange);
      cursorRequest.onsuccess = function(e) {
        /* called when the cursor request succeeds
        */
        var result, t;
        result = e.target.result;
        if (!(result != null)) return;
        /* display the log record, skipping the last
        */
        t = result.value.t;
        if (+t === +now) return;
        $('#log').prepend($("<li>You have already visited this page on " + (moment(t).format('MMMM Do YYYY, h:mm:ss a')) + "</li>"));
        return result["continue"]();
      };
      tx.oncomplete = function() {
        /* called when the transaction ends
        */        return console.log('Transaction complete.');
      };
      /* close the connection to the DB
      */
      return db.close();
    };
  };

}).call(this);

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>IndexedDB</title>
        <script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
        <script src="moment+langs.js"></script>
        <link type="text/css" href="index.css" rel="stylesheet"/>
        <script src="index.js"></script>
    </head>
    <body onload="main()">
        <p id='welcome'>Welcome! Try to reload the page...</p>
        <ol id='log'></ol>
    </body>
</html>

index.coffee

window.main = () ->
    ### the value '2' as DB version makes me laugh, but is the only way I can make it work... ###
    request = indexedDB.open('openlog', 2)
    
    request.onupgradeneeded = () ->
        ### called whenever the DB changes version. triggers when the DB is created ###
        db = request.result
        store = db.createObjectStore('timestamps', {keyPath: 'id', autoIncrement: true})
        
        console.log('Database created or upgraded.')
        
    request.onsuccess = () ->
        ### called when the connection with the DB is opened successfully ###
        db = request.result
        console.log('Database connection opened.')
        
        ### open a transaction ###
        tx = db.transaction('timestamps', 'readwrite')
        store = tx.objectStore('timestamps')
        
        ### store a new record with the current timestamp ###
        now = new Date()
        store.put {t: now}
        
        ### get everything in the store ###
        keyRange = IDBKeyRange.lowerBound(0)
        cursorRequest = store.openCursor(keyRange)
        
        cursorRequest.onsuccess = (e) ->
            ### called when the cursor request succeeds ###
            result = e.target.result
            if not result?
                return
                
            ### display the log record, skipping the last ###
            t = result.value.t
            if +t == +now
                return
                
            $('#log').prepend $("<li>You have already visited this page on #{moment(t).format('MMMM Do YYYY, h:mm:ss a')}</li>")
            
            result.continue()
            
        tx.oncomplete = () ->
            ### called when the transaction ends ###
            console.log('Transaction complete.')
            
        ### close the connection to the DB ###
        db.close()
        

index.css

#log {
  font-family: sans-serif;
  font-size: 16pt;
  list-style-type: none;
  margin-top: 42px;
  color: black;
}
#log li {
  margin-bottom: 0.2em;
}
#log li + li {
  color: #555555;
}
#log li + li + li {
  color: #777777;
}
#log li + li + li + li {
  color: #999999;
}
#log li + li + li + li + li {
  color: #bbbbbb;
}
#log li + li + li + li + li + li {
  color: #dddddd;
}

#welcome {
  font-size: 32px;
  font-family: sans-serif;
  margin-top: 32px;
  margin-left: 112px;
}

body {
  margin-left: 128px;
}

index.sass

#log
    font-family: sans-serif
    font-size: 16pt
    list-style-type: none
    margin-top: 42px
    color: black
    
    li
        margin-bottom: 0.2em
        
    li + li
        color: #555
    li + li + li
        color: #777
    li + li + li + li
        color: #999
    li + li + li + li + li
        color: #BBB
    li + li + li + li + li + li
        color: #DDD
        
#welcome
    font-size: 32px
    font-family: sans-serif
    margin-top: 32px
    margin-left: 112px
    
body
    margin-left: 128px