I am working on a browser extension for Firefox and Chrome, I currently have the following blob of a code:
$("<div id=\"discardedItems\"><div id=\"ext-helper-grid-header\"><span id=\"ext-helper-grid-collapse-indicator\"></span> <span id=\"ext-helper-grid-count\"></span> item(s)</div><div id=\"ext-helper-grid\"></div></div><br /><hr /><br />").insertBefore("#items-grid");
It's a blob, I don't like it. I'd rather have the html code laid out in a separate file:
/discarded-section.html:
<div id="discardedItems">
<div id="ext-helper-grid-header">
<span id="ext-helper-grid-collapse-indicator"></span>
<span id="ext-helper-grid-count"></span> item(s)
</div>
<div id="ext-helper-grid"></div>
</div>
<br />
<hr />
<br />
And then I added the file to my manifest.json file:
"web_accessible_resources": [
{
"resources": [ "images/info.png", "discarded-section.html" ],
"matches": ["<all_urls>"]
}
],
Now I was hoping to be able to fetch the file and by default the extension would try to load it locally from the extension file, but the default behaviour is that is tries to load it from the website I'm currently on, which result in a 404 error.
I've tried the following code, without much success:
/scripts/content.js
function readFile(_path, _cb){
fetch(_path, {mode:'same-origin'}) // <-- important
.then(function(_res) {
return _res.blob();
})
.then(function(_blob) {
var reader = new FileReader();
reader.addEventListener("loadend", function() {
_cb(this.result);
});
reader.readAsText(_blob);
});
};
readFile('../discarded-section.html', function(_res){
console.log(_res); // <-- result (file content)
//$(_res).insertBefore("#items-grid");
});
Note that either ../discarded-section.html or /discarded-section.html lead to the same result of attempting to load that page on the website, and not from the extension.
Alternatively, if I had a function to return me the absolute path of the extension for Firefox or Chrome, it would probably work?
ie:
moz-extension://e9a69233-6b12-2b38-b287-3fc12870a02/discarded-section.html
or
chrome-extension://loremipsumasdasdkas/discarded-section.html
What solution have you found to load the content of a local file from the extension with javascript (using jquery is fine)?