我试图使自己熟悉Firefox自举插件。考虑以下示例:
// bootstrap.js
'use strict'
function alert(message) {
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
prompts.alert(null, "from my extension", message);
}
try {
Components.utils.import('chrome://my-ext/content/foo.jsm');
alert('ok');
} catch(e) {
alert(e);
}
而
chrome://my-ext/content/foo.jsm
只是this.EXPORTED_SYMBOLS = [];
。上面的代码示例的问题在于它并非每次都起作用。它可能无法通过
NS_ERROR_FILE_NOT_FOUND
而不是导入失败,或者可能会说“确定”-尽管后来启动浏览器时,我可以通过位置栏访问foo.jsm
。这是否意味着我不应该在顶层导入任何内容,因为可能尚未完成chrome注册,或者其他问题?
最佳答案
N.B.以下是我的经验,可能不确定
引导加载项的bootstrap.js在浏览器启动时以及创建任何WINDOW或DOM之前运行。
bootstrap.js还具有执行的顺序和特定格式。
以上示例是bootstrap.js的方式吗?
您可以在任何地方导入Firefox模块(尽管我总是会始终这样做)。
最好在Components.utils.import('chrome://my-ext/content/foo.jsm');
内执行function startup(data, reason) { ... }
附加说明/建议:
通常,我会在函数外部分配var prompts
,这样就不会在每次运行函数时都重新分配它。
我也将使用Services.jsm
以便于使用(但没有任何区别),例如:
Components.utils.import('resource://gre/modules/Services.jsm');
// then anywhere in the code
Services.prompt.alert(null, title, text);
通常,我在JS / JSM上执行所有Firefox内置模块导入
Components.utils.import()
Firefox内置了Firefox内置模块(而非插件模块),因此无需
Components.utils.unload()
即可。