Search code examples
javascriptgoogle-chrome-app

How to access internal resources from background.js


In a Google Chrome application is it possible to access bundled data files from within the background.js script?

E.g. if I had a file called data.json that I include with the app, is there a JavaScript API that I could use in the background.js script to get at the files contents?

With the example bundle directory structure:

/app/manfifest.json
/app/backround.js
/app/data.json

I want to do something like:

chrome.app.runtime.onLaunched.addListener(function() {
  data = unknown.api.loadFileSync("data.json");
  // do stuff with data
  // ...
});

Solution

  • In the API docs you can get the DirectoryEntry object for the package directory, and then using the HTML5 FileSystem API get the contents of the file. The API function is chrome.runtime.getPackageDirectoryEntry.

    chrome.runtime.getPackageDirectoryEntry(function (dirEntry) {
        dirEntry.getFile("data.json", undefined, function (fileEntry) {
        fileEntry.file(function (file) {
                var reader = new FileReader()
                reader.addEventListener("load", function (event) {
                    // data now in reader.result                                                        
                    console.log(reader.result);
                });
                reader.readAsText(file);
            });
        }, function (e) {
            console.log(e);
        });
    });