Download JSON file in Firefox Addon Page Script, all locally inside the package

I am developing a Firefox extension using the Addon SDK and uploading some data that is stored in one package as a separate file: "data.json". It must be downloaded from the script page, that is, "loader.js", which is included in the "panel.html", using script src tags.

The structure looks like this:

+data panel.html panel.js loader.js data.json ... +lib main.js ... 

panel.html has:

 <script type="text/javascript" src="loader.js"></script> 

Initially, we stored the data simply in the js file as "data.js" and included it from "panel.html" using the src script tags, and it worked without problems. However, when we sent the add-on to the Mozilla Addon website, this was considered as one of the problems to fix, stating that we needed to use a non-executable format, such as a JSON file, to make it more secure.

Now the problem seems that "loader.js" is not allowed to make an AJAX request to "data.json". (Using the jQuery call $ .ajax () returns without success, giving error code 0). So the solution I was thinking about is to load "data.json" from "main.js" using the SDK () request function and somehow pass it to "loader.js", the script page. But this seems complicated, because, as I understand it, the data must first be sent to the script content, and then from there to the script page. And this should happen when the script page loads! I am confused by this since I'm not sure if I am missing a more practical solution, or is it really something complicated, what am I trying to do by simply loading local JSON data into a package on a local script page?

+6
source share
1 answer

Here is an example of an add-in constructor that explores and approaches this.

Firstly, you can load the json file from the data and parse it using self.data.load:

 let data = require('self').data; let taps_data = JSON.parse(data.load('taps.json')); 

This loads synchronously, so you don’t often do this, and in the example it will only happen when the firstst add-in becomes active in the browsing session.

Then you should use content scripts and messaging to transfer data to the panel.

In main.js script:

 panel.on('show', function() { if (!loaded) panel.port.emit('taps-data', taps_data); }); 

In the contents of the script:

 self.port.on('taps-data', function(data) { $('#list').html(''); data.forEach(function(item) { $('#list').append('<div>'+ item.name +'</div>'); }); self.port.emit('taps-loaded'); }); 

I do a bit of extra work to make sure that I only output the data once. The data, FYI, is saved from live beer barrels api data from my local pub .

+7
source

All Articles