Chrome app access external resources with JavaScri

2019-07-27 05:36发布

问题:

I am building a Chrome app that visualizes some data. My data is collected separately and is stored in a local folder that is unrelated to the Chrome app. I am using Angular + D3, and I want my app to grab the data from a specified folder. How can I do that?

Currently, I am trying to use the $http service, but it doesn't work they way I want. Here is the code:

var app = angular.module('myApp', []);

app.controller('dataController', ['$scope', '$http', function($scope, $http) {
  $http.get('../data/file.json').success(function(data) {
    $scope.data = data;
    console.log($scope.data);
  });
}]);

The problem is that in this case the path ../data/file.json can only lead to a file inside the application's folder, i.e., I cannot specify an arbitrary directory/file on my filesystem. How can I go about this? In general, can I have an external folder with resources that a Chrome app can use (read only is enough for me)?

回答1:

To gain access to an arbitrary directory, you need to use the fileSystem.chooseEntry function, which will prompt the user to select a directory, and then return a handle to you. Here is an example:

You must first add the necessary permissions to your manifest file:

"permissions": [
      { "fileSystem": 
       ["directory", "retainEntries"] 
      }
  ]

To read a file:

chrome.fileSystem.chooseEntry({ type: 'openDirectory' }, function (dirEntry) {
    dirEntry.getFile('file.json', {}, function (fileEntry) {
        fileEntry.file(function (file) {
            var reader = new FileReader();

            reader.onloadend = function (e) {
                var result = JSON.parse(this.result);
                console.log(result);
            };

            reader.readAsText(file);
        });
    });
});

To retain your access to a directory across sessions, you can use retainEntry to get an id which you can save, and later use with restoreEntry to regain access to the directory. This way the user only has to select the directory once.