How to reference a JavaScript file in Lib from an

2019-07-21 16:15发布

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

enter image description here

The problem is that the file popup.html needs to reference stackapi.js. But I have absolutely no clue how to do that. Looking through the 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.

3条回答
够拽才男人
2楼-- · 2019-07-21 16:54

In add-ons built with the Add-on SDK (and the Builder is merely a web interface for the SDK) web pages cannot access extension modules directly - they don't have the necessary privileges. If you simply need to include a JavaScript file from the web page then you should put that file into the data directory. However, it won't have any special privileges then (like being able to call require()).

You don't tell how you are using popup.html but I guess that it is a panel. If you want that page to communicate with your add-on you need to use content scripts. Put a content script file into the data directory, assign it to your panel via contentScriptFile parameter. See documentation on 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 a message back then.

查看更多
狗以群分
3楼-- · 2019-07-21 17:07

Had to go through the same scenario, but solution by jongo45 does not seem to work anymore. Somehow found a solution which worked for me. Posting below as it might help someone in need.

Below code obtains list of all files under "lib/subdir".

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'));
查看更多
贪生不怕死
4楼-- · 2019-07-21 17:09

You can get the url of the stackapi.js file by navigating up from the /data folder and back down the /lib folder like so:

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

Then use that resource url in the contentScriptFile parameter when attaching scripts to what I assume is going to be popup.html.

You'll need to check which environment you're currently in to determine if you need to add any references to the exports object to make them accessible from within the addon.

if(typeof(exports)!="undefined"){
  exports.something=function(){...};
}
查看更多
登录 后发表回答