Save and Fetch Data

The sample from Lab 3 uses a static array of Todos. Every time your app restarts, whatever you've changed is lost. In this section, we will save every change using chrome.storage.sync.

This lets you store small things that automatically sync to the cloud if you are online and logged in to Chrome. If you are offline or unlogged, it saves locally and transparently: you don't have to handle online check and offline fallback in your application.

Save your Todos in the cloud

Note: Chrome Sync Storage is not intended to be used as a generic database. There are several restrictions on the amount of information you can save, so it is more appropriate to save settings and other small chunks of data.

Update manifest

Request permission to use storage in your manifest. Permissions are the same in the AngularJS manifest.json and JavaScript manifest.json:

{
  ... ,
  "permissions": ["storage"]
}

Update controller

Change your controller to get the Todo list from syncable storage instead of a static list: AngularJS controller.js or JavaScript controller.js.

Angular
JavaScript
// Notice that chrome.storage.sync.get is asynchronous
chrome.storage.sync.get('todolist', function(value) {
  // The $apply is only necessary to execute the function inside Angular scope
  $scope.$apply(function() {
    $scope.load(value);
  });
});

// If there is saved data in storage, use it. Otherwise, bootstrap with sample todos
$scope.load = function(value) {
  if (value && value.todolist) {
    $scope.todos = value.todolist;
  } else {
    $scope.todos = [
      {text:'learn angular', done:true},
      {text:'build an angular app', done:false}];
  }
}

$scope.save = function() {
  chrome.storage.sync.set({'todolist': $scope.todos});
};
    
  /**
   * Listen to changes in the model and trigger the appropriate changes in the view
   **/
  model.addListener(function(model, changeType, param) {
    if ( changeType === 'removed' || changeType === 'archived' || changeType === 'reset') {
      redrawUI(model);
    } else if ( changeType === 'added' ) {
      drawTodo(model.todos[param], list);
    } else if ( changeType === 'stateChanged') {
      updateTodo(model.todos[param]);
    }
    storageSave();
    updateCounters(model);
  });

// If there is saved data in storage, use it. Otherwise, bootstrap with sample todos
  var storageLoad = function() {
    chrome.storage.sync.get('todolist', function(value) {
      if (value && value.todolist) {
        model.setTodos(value.todolist);
      } else {
        model.addTodo('learn Chrome Apps', true);
        model.addTodo('build a Chrome App', false);
      }
    });
  }

  var storageSave = function() {
    chrome.storage.sync.set({'todolist': model.todos});
  };
    

Update view

In the view, AngularJs index.hmtl or JavaScript index.html, save the data whenever it changes. In AngularJS, we call save() explicitedly but there are many ways of doing this. For example, you could also use $watchers on the scope.

Angular
JavaScript
...
       [ <a href="" ng-click="archive() || save()">archive</a> ]
...
            <input type="checkbox" ng-model="todo.done" ng-change="save()">
...
       <form ng-submit="addTodo() || save()">
...
    
<form>
  <input type="text" size="30"
         placeholder="add new todo here">
  <input class="btn-primary" type="submit" value="add">
</form>
    

Check the results

Check the results by reloading the app: open the app, right-click and select Reload App. You can now add Todo items, close the app, and the new items will still be there when you reopen the app.

If you get stuck and want to see the app in action, go to chrome://extensions, load the unpacked app, and launch the app from a new tab: Angular JS 1_storage_sync or JavaScript 1_storage_sync.

Handle drag-and-dropped files and URLs

Suppose you want to create Todos associated with local files and/or URLs. The natural way of doing this is to accept dropped items. It's simple enough to add drag-and-drop support in a Chrome App using the standard HTML5 Drag-and-Drop API.

Update controller

In the controller, add code to handle the events of dragover, dragleave, and drop: AngularJS controller.js or JavaScript controller.js.

Angular
JavaScript
var defaultDropText = "Or drop files here...";
$scope.dropText = defaultDropText;

// on dragOver, we will change the style and text accordingly, depending on
// the data being transferred
var dragOver = function(e) {
  e.stopPropagation();
  e.preventDefault();
  var valid = e.dataTransfer && e.dataTransfer.types
    && ( e.dataTransfer.types.indexOf('Files') >= 0
      || e.dataTransfer.types.indexOf('text/uri-list') >=0 )
  $scope.$apply(function() {
    $scope.dropText = valid ? "Drop files and remote images and they will become Todos"
        : "Can only drop files and remote images here";
    $scope.dropClass = valid ? "dragging" : "invalid-dragging";
  });
}

// reset style and text to the default
var dragLeave = function(e) {
  $scope.$apply(function() {
    $scope.dropText = defaultDropText;
    $scope.dropClass = '';
  });
}

// on drop, we create the appropriate TODOs using dropped data
var drop = function(e) {
  e.preventDefault();
  e.stopPropagation();

var newTodos=[];
  if (e.dataTransfer.types.indexOf('Files') >= 0) {
    var files = e.dataTransfer.files;
    for (var i = 0; i < files.length; i++) {
      var text = files[i].name+', '+files[i].size+' bytes';
      newTodos.push({text:text, done:false, file: files[i]});
    }
  } else { // uris
    var uri=e.dataTransfer.getData("text/uri-list");
    newTodos.push({text:uri, done:false, uri: uri});
  }

$scope.$apply(function() {
    $scope.dropText = defaultDropText;
    $scope.dropClass = '';
    for (var i = 0; i < newTodos.length; i++) {
      $scope.todos.push(newTodos[i]);
    }
    $scope.save();
  });
}

document.body.addEventListener("dragover", dragOver, false);
document.body.addEventListener("dragleave", dragLeave, false);
document.body.addEventListener("drop", drop, false);
    
var defaultDropText = "Or drop files here...";

var dropText = document.getElementById('dropText');
dropText.innerText = defaultDropText;

// on dragOver, we will change the style and text accordingly, depending on
// the data being transfered
var dragOver = function(e) {
  e.stopPropagation();
  e.preventDefault();
  var valid = isValid(e.dataTransfer);
  if (valid) {
    dropText.innerText="Drop files and remote images and they will become Todos";
    document.body.classList.add("dragging");
  } else {
    dropText.innerText="Can only drop files and remote images here";
    document.body.classList.add("invalid-dragging");
  }
}

var isValid = function(dataTransfer) {
  return dataTransfer && dataTransfer.types
    && ( dataTransfer.types.indexOf('Files') >= 0
      || dataTransfer.types.indexOf('text/uri-list') >=0 )
}

// reset style and text to the default
var dragLeave = function(e) {
  dropText.innerText=defaultDropText;
  document.body.classList.remove('dragging');
  document.body.classList.remove('invalid-dragging');
}

// on drop, we create the appropriate TODOs using dropped data
var drop = function(e, model) {
  e.preventDefault();
  e.stopPropagation();
  if (isValid(e.dataTransfer)) {
    if (e.dataTransfer.types.indexOf('Files') >= 0) {
      var files = e.dataTransfer.files;
      for (var i = 0; i < files.length; i++) {
        var text = files[i].name+', '+files[i].size+' bytes';
        model.addTodo(text, false, {file: files[i]});
      }
    } else { // uris
      var uri=e.dataTransfer.getData("text/uri-list");
      model.addTodo(uri, false, {uri: uri});
    }
  }

  dragLeave();
}

exports.setDragHandlers = function(model) {
  document.body.addEventListener("dragover", dragOver, false);
  document.body.addEventListener("dragleave", dragLeave, false);
  document.body.addEventListener("drop", function(e) {
      drop(e, model);
    }, false);
}
    

Update view

If using AngularJS, let's move the Angular scope definition from the div to the body in the AngularJS index.html file to make all the area of the window accept the drop event and still work on the same scope. Also, let's associate the body's CSS class with the Angular controller's class, so we can change the class directly in the scope and have it automatically changed in the DOM:

Angular
<body ng-controller="TodoCtrl" ng-class="dropClass">
<!-- remember to remove the ng-controller attribute from the div where it was before -->
    

Add a message placeholder (in AngularJS index.html or JavaScript index.html) to warn the user that some types of dragging are not allowed:

Angular
JavaScript
<div>
 {{dropText}}
</div>
    
<div id="dropText">
</div>
    

Update stylesheet

Add appropriate styling for the dragging and invalid-dragging CSS classes in the css. AngularJS todo.css and JavaScript todo.css are the same. Here we used a green or red background color animation:

@-webkit-keyframes switch-green {
  from { background-color: white;} to {background-color: rgb(163, 255, 163);}
}
@-webkit-keyframes switch-red {
  from { background-color: white;} to {background-color: rgb(255, 203, 203);}
}
.dragging {
  -webkit-animation: switch-green 0.5s ease-in-out 0 infinite alternate;
}

.invalid-dragging {
  -webkit-animation: switch-red 0.5s ease-in-out 0 infinite alternate;
}

Check the results

Check the results by reloading the app: open the app, right-click and select Reload App. You can now drag files into the Todo list.

If you get stuck and want to see the app in action, go to chrome://extensions, load the unpacked app, and launch the app from a new tab: AngularJS 2_drop_files or JavaScript 2_drop_files.

Challenge

The current code only saves the file reference, but it doesn't open the file. Using the HTML5 Filesystem API, save the file contents in a sandboxed filesystem. When the Todo item is archived, remove the corresponding file from the sandboxed filesystem. Add an "open" link on each Todo that has an associated file. When the item is clicked and the file exists in the sandboxed filesystem, use the Chrome App Filesystem API to request a writable FileEntry from the user. Save the file data from the sandboxed filesystem into that entry.

Tip: managing file entries using the raw HTML5 Filesystem API is not trivial. You might want to use a wrapper library, like Eric Bidelman's filer.js.

Takeaways

You should also read

Manage Data tutorial

What's next?

In 5 - Manage App Lifecycle, you will learn the basics of the Chrome App lifecycle.