How to read a file from chrome extension?

I have popup.html where popup.js is called when a popup is loaded by clicking the browser action. There I programmatically embed content scripts using chrome.tabs.executeScript() . I need to add one element to the body of the page. How can I insert HTML code from another .html file into the extension, because it is much easier to maintain such code. I thought about accessing it in popup.js (is there any API call for this?), And then in the code attribute to insert the contents of the script code with a string of the received HTML code.

I saw some methods using XMLHttpRequest from the contents of the script, but is there any way to avoid this? I tried with chrome.fileSystem , but this is for Chrome apps, not extensions.

+8
javascript google-chrome google-chrome-extension
source share
1 answer

As the comment mentioned, it is only about making a GET request to chrome.runtime.getURL("myfile.html") , where "myfile.html" is the relative path (from the extension root) to the file you want.

You can do this with raw XHR or, if you use jQuery, use $.ajax .

To do this from the contents of the script, you need to declare it in "web_accessible_resources" .


Since you do not want this, yes, there is another way (not available for content scripts).

You can get the read-only HTML5 file system for your extension files using 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 much more complicated than an XHR request. This is probably only possible if you want to list files .

+14
source share

All Articles