How to reference a JavaScript file in Lib from an HTML file in Data?

I decided to give Mozilla Add-on Builder a try. My directory structure looks something like this:

enter image description here

The problem is that the popup.html file should reference stackapi.js . But I have no idea how to do this. Looking through Mozilla docs, there seems to be a way to do the opposite:

 var data = require("self").data; var url_of_popup = data.url("popup.html"); 

This allows scripts in Lib to access data files in Data. But I need to do the opposite.

+2
source share
3 answers

In add-ons created using the Add-on SDK (and Builder is just a web interface for the SDK), web pages cannot directly access extension modules - they do not have the necessary privileges. If you just need to add the JavaScript file from the web page, you must put this file in the data directory. However, it will then not have any special privileges (for example, the ability to call require() ).

You will not tell how you use popup.html , but I think this is panel . If you want this page to link to your add-in, you need to use content scripts. Put the contents of the script in the data directory, assign it to your panel using the contentScriptFile parameter. See the documentation for content scripts , the content script will be able to use self.postMessage() to send messages to the extension, the extension can perform the necessary operations and send the message then.

+3
source

You can get the URL of the stackapi.js file by moving from the /data folder and open the /lib folder as follows:

 var url=require("sdk/self").data.url("../lib/stackapi.js"); 

Then use this resource URL in the contentScriptFile parameter when attaching scripts to what I assume will be popup.html .

You will need to check what environment you are currently in to determine if you need to add links to the exports object to make them accessible from the addon.

 if(typeof(exports)!="undefined"){ exports.something=function(){...}; } 
+2
source

The same scenario should go through, but the jongo45 solution doesn't seem to work anymore. Somehow I found a solution that worked for me. The wiring is lower, as this may help someone need it.

Below the code gets a list of all the files in the "lib / subdir" section.

 const fileIO = require("sdk/io/file"); const fspath = require("sdk/fs/path"); const {Cc, Ci} = require("chrome"); const currDir = Cc["@mozilla.org/file/directory_service;1"] .getService(Ci.nsIDirectoryServiceProvider) .getFile("CurWorkD", {}).path; const listOfFiles = fileIO.list(fspath.resolve(currDir,'lib/subdir')); 
0
source

Source: https://habr.com/ru/post/1494668/


All Articles