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

混江龙づ霸主 提交于 2019-12-24 04:35:38

问题


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

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.


回答1:


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.




回答2:


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(){...};
}



回答3:


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'));


来源:https://stackoverflow.com/questions/8706976/how-to-reference-a-javascript-file-in-lib-from-an-html-file-in-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!