Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(). I need to append one element to page's body. How can I insert HTML code from different .html file within extension, because it's much easier to maintain the code like that. I was thinking of accessing it within popup.js (is there some API call for that?) and then within code attribute to insert content script code with string of retrieved HTML code.

I saw some methods using XMLHttpRequest from content script, but is there to avoid that? I tried with chrome.fileSystem, but that's for chrome apps and not extensions.

like image 858
Tommz Avatar asked Mar 04 '15 15:03

Tommz


People also ask

How do I use Chrome source viewer extension?

Using the Chrome Extension Source Code Viewer Now that it is installed, you can go into the Google Chrome Web Store and view the source code of any app. Just click on the yellow icon in the location bar and you'll be given a choice to either download the file as a zip file or view it online.

How do I open a file extension?

To open up your extensions page, click the menu icon (three dots) at the top right of Chrome, point to “More Tools,” then click on “Extensions.” You can also type chrome://extensions/ into Chrome's Omnibox and press Enter.


1 Answers

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 = new FileReader();
      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.

like image 78
Xan Avatar answered Oct 07 '22 04:10

Xan