Skip to content Skip to sidebar Skip to footer

How To Read File From Chrome Extension?

I have popup.html where popup.js is invoked when popup is loaded by clicking on browser action. There I'm programmatically injecting content scripts with chrome.tabs.executeScript(

Solution 1:

As a comment mentioned, it's just a question of making a GET request to chrome.runtime.getURL("myfile.html"), where "myfile.html" is the relative path (from the root of the extension) to the file that you want.

You can do that with raw XHR or, if you're using jQuery, using $.ajax.

To do it from a content script, you need to declare it in "web_accessible_resources".


Since you don't want that, yes, there is another way (not available to content scripts).

You can obtain a read-only HTML5 Filesystem access to your extension's files with chrome.runtime.getPackageDirectoryEntry:

chrome.runtime.getPackageDirectoryEntry(function(root) {
  root.getFile("myfile.html", {}, function(fileEntry) {
    fileEntry.file(function(file) {
      var reader = newFileReader();
      reader.onloadend = function(e) {
        // contents are in this.result
      };
      reader.readAsText(file);
    }, errorHandler);
  }, errorHandler);
});

As you can see, this is vastly more complicated than an XHR request. One would probably use this only if one wants to list the files.

Post a Comment for "How To Read File From Chrome Extension?"