6

I'm developing a chrome extension and I would like to store some data in a file permanently in the users system so that I can retrieve that data every time the user runs the extension.

Is there a way I can accomplish this with the chrome javascript API?

Thanks in advance.

djk
  • 943
  • 2
  • 9
  • 27
asamolion
  • 828
  • 2
  • 12
  • 24

2 Answers2

7

From your description, it sounds like you would be better off using the Chrome Storage API, which writes data into a browser-managed database. It is kept across sessions and browser-restarts.

chrome.storage.sync.set({'theKey': theValue}, optionalSuccessCallback);

Use any number of keys and any value as long as it is serializable. This is fast and especially useful for configuration settings and alike. Your extension needs to request permission:

"permissions": ["storage"]

If your really want to create files (e.g. a bunch of mp3's to use as actual files later), Anatoly is right, use webkitRequestFileSystem. It requires quite a few callbacks:

function onInitFs(fs) {
  fs.root.getFile('log.txt', {create: true}, function(fileEntry) {

    // Create a FileWriter object for our FileEntry (log.txt).
    fileEntry.createWriter(function(fileWriter) {

      fileWriter.onwriteend = function(e) {
        console.log('Write completed.');
      };

      fileWriter.onerror = function(e) {
        console.log('Write failed: ' + e.toString());
      };

      // Create a new Blob and write it to log.txt.
      var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});

      fileWriter.write(blob);

    }, errorHandler);
  }, errorHandler);
}

window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);
Xan
  • 74,770
  • 16
  • 179
  • 206
djk
  • 943
  • 2
  • 9
  • 27
  • 1
    Grain of salt: for the Storage API (and the HTML FileSystem API) to really use "any number of keys and any value" you may need the `"unlimitedStorage"` permission, and there are still quotas on `sync` storage. – Xan Jun 14 '16 at 15:23
1

It's possible with webkitRequestFileSystem. You'll be able to access sandboxed persistent folder to create and read files from.

Anatoly Sazanov
  • 1,814
  • 2
  • 14
  • 24