我正在尝试使用以下命令在无需重新启动的附加组件中加载自定义模块:
chrome/content/modules/Test.jsm:
var EXPORTED_SYMBOLS = [ 'Test' ];
let Test = {};
chrome.manifest:
content test chrome/content/
bootstrap.js:
const Cu = Components.utils;
// Tried this first, but figured perhaps chrome directives aren't loaded here yet
// let test = Cu.import( 'chrome://test/modules/Test.jsm', {} ).Test;
function install() {
let test = Cu.import( 'chrome://test/modules/Test.jsm', {} ).Test;
}
function uninstall() {
let test = Cu.import( 'chrome://test/modules/Test.jsm', {} ).Test;
}
function startup() {
let test = Cu.import( 'chrome://test/modules/Test.jsm', {} ).Test;
}
function shutdown() {
let test = Cu.import( 'chrome://test/modules/Test.jsm', {} ).Test;
}
但是,我收到以下类型的警告消息(此消息用于 shutdown()
,但对于所有函数以及全局范围内的早期尝试基本相同):
1409229174591 addons.xpi WARN Exception running bootstrap method shutdown on [email protected]: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXPCComponents_Utils.import]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: resource://gre/modules/addons/XPIProvider.jsm -> file:///test/bootstrap.js :: shutdown :: line 21" data: no] Stack trace: shutdown()@resource://gre/modules/addons/XPIProvider.jsm -> file:///test/bootstrap.js:21 < XPI_callBootstrapMethod()@resource://gre/modules/addons/XPIProvider.jsm:4232 < XPI_updateAddonDisabledState()@resource://gre/modules/addons/XPIProvider.jsm:4347 < AddonWrapper_userDisabledSetter()@resource://gre/modules/addons/XPIProvider.jsm:6647 < uninstall()@extensions.xml:1541 < oncommand()@about:addons:1 <
chrome.manifest
指令在 bootstrap.js
中尚不可用吗?或者我正在尝试某种安全违规行为?或者我只是做了一些微不足道的错误?
我希望实现的是,我可以做如下的事情:
chrome/content/modules/Test.jsm:
var EXPORTED_SYMBOLS = [ 'Test' ];
let Test = {
install: function( data, reason ) {
},
/* etc */
bootstrap: function( context ) {
context.install = this.install;
context.uninstall = this.uninstall;
context.startup = this.startup;
context.shutdown = this.shutdown;
}
}
bootstrap.js:
const Cu = Components.utils;
Cu.import( 'chrome://test/modules/Test.jsm' );
Test.bootstrap( this );
也许一开始就有点过头了,但我只是喜欢隐藏模块和/或对象中的实现并保持 bootstrap.js
super 干净的想法。
如果您碰巧对如何通过其他方式实现这一目标有建议:我洗耳恭听。
最佳答案
是的,你可以,但你的路径是错误的。
只需这样做:
let test = Cu.import( 'chrome://test/content/modules/Test.jsm', {} ).Test;
注意/content/
您不必执行.Test
,除非您希望小写的test
来保存它。你可以这样做:
Cu.import( 'chrome://test/content/modules/Test.jsm');
并用作Test.blah
,其中blah 是JSM 模块中的任何内容。
此代码可以放在任何地方,不必位于 install
函数中。
确保卸载自定义 JSM 模块,否则可能会导致僵尸隔间,这对内存不利。阅读此处:
关于firefox-addon - 我可以在无需重新启动的附加组件的 bootstrap.js 中加载自定义 jsm 模块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549173/