我对Mozilla扩展开发非常陌生,即使我才刚知道扩展和附加开发都不一样
而且我对在MDN(Mozilla开发人员网络)上看到的内容非常满意。
我要在安装我的附加组件后立即执行script'content_script.js',因此用户无需重新启动浏览器。
我只是拖放我的xpi文件并安装它,然后单击网页上的一个按钮,该按钮会将消息发送到我的附件,但是我的附件仅在我重新加载网页后才收听此消息。
//main.js
var chrome = require("chrome");
chrome.runtime.onInstalled.addListener(function(){
executeScript (contentscript.js) in tabs});
//also I tried
browser.runtime.onInstalled.addListener
当我发现它用于Mozilla扩展而不是用于附件时,我正在尝试使用此方法,因为它给我带来了浏览器未定义和
chrome.runtime
未定义的错误。然后,我在
onInstalled()
中找到了AddonManager.addAddonListener()
。但是,我仍然很困惑如何在附加组件中使用它。
无论我尝试哪种方式,都会给我带来错误。
//main.js
const { AddonManager } = require("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");
AddonManager.addAddonListener.onInstalled.addListener(function(){
console.log('installed');
tabs.executeScript(tabId, "../data/content_script.js", function(result) { console.log('result ='+result); });
});
下面的代码消除了该错误,但也不起作用:
const { AddonManager } = require("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");
var listener = {
onInstalled: function(addon) {
console.log('installed');
console.log(addon);
tabs.executeScript(tabId, "../data/content_script.js", function(result) { console.log('result ='+result); });
}
};
AddonManager.addAddonListener(listener);
我的package.json看起来像这样
{
"title": "test",
"name": "test",
"version": "1.0.0",
"description": "test addon corp",
"main": "lib/main.js",
"author": "test",
"engines": {
"firefox": ">=38.0a1",
"fennec": ">=38.0a1"
},
"license": "MIT",
"keywords": [
"jetpack"
]
}
main
包含main.js,但仍未执行,因为当我重新加载页面时,附加组件才起作用。我认为我做的完全错误,我在Chrome扩展程序中做到了,这很容易,但是我对Mozilla插件没有任何想法。我什至无法达到“已安装”状态。执行content_script很遥远。
最佳答案
看来您遇到了一些问题:
您仍在混合使用WebExtensions和附加SDK
附件SDK没有您要查找tabs.executeScript()
的tab.attach()
这样的方法。对于活动选项卡,它为tabs.activeTab.attach()
。
当前正在安装的附件的安装的AddonManager
onInstalled
事件发生在运行该附件的任何代码之前。因此,对于正在侦听的加载项,您将不会收到此事件。AddonManager
主要用于您的加载项,以便能够监视涉及其他加载项的活动。它在监视执行监视的附加程序的活动方面的有用性受到限制。
如果用户在删除附件之前将其禁用,则可以获取AddonManager
onDisabled
事件。如果用户直接将其删除,则只会得到一个onUninstalling
事件。
当内容脚本由作为使用console.log()
测试的主要加载项加载的加载项附加到内容脚本时,您可能会遇到以下问题:内容脚本中的jpm run
无法显示在浏览器控制台中。输出在执行jpm run
的控制台窗口中可用。虽然输出是设计使然进入控制台窗口的,但我感觉输出没有进入浏览器控制台(除了控制台窗口)还是错误或功能不足。
将内容脚本加载到about:*
页面中所导致的某些行为与将其加载到普通网页中不同。此行为可以包括使console.log()
输出仅显示为好像是使用dump()
输出的(即,它不会显示在浏览器控制台中,而是显示在执行Firefox / jpm run
的控制台中)。如果您尝试这样做,则将需要尝试进行一些尝试。
您已经说过:“我认为我的main.js在安装后没有立即运行。”这种信念可能是由于没有在正确的位置查找console.log()
输出,即Browser Console。因此,我在下面的附加组件中自动打开了浏览器控制台。
在安装附加组件时,将运行package.json键"main"
中指定的JavaScript文件。它也可以在Firefox启动时运行。
您可以具有一个exports.main
函数,该函数在评估和执行"main"
JavaScript文件中的代码后会自动调用。此功能可用于查找执行加载项的原因。可能的原因是install
,enable
,startup
,upgrade
和downgrade
。下面的附加组件演示了何时执行此代码并将reason
传递给它。
为了演示各种内容,我编写了一个Firefox附加SDK扩展,它既可以加载两个内容脚本,又可以监听AddonManager
事件。我制作了该插件的两个版本,它们的名称和ID只是在各自的package.json文件中分配给它们的不同。两个附加组件是installinfo@ex1
和installinfo@ex2
。
第一个加载项installinfo@ex1
是通过在其目录中运行jpm run
加载的。通过拖放installinfo@ex2
为它创建的.xpi,安装第二个附件jpm xpi
。使用Firefox UI,我立即导航到about:addons
(在OSX上为Ctrl-Shift-A,Cmd-Shift-A),然后继续首先禁用installinfo@ex2
。然后“删除” installinfo@ex2
;然后刷新about:addons
页面,以使其无法“撤消”删除。然后,我退出Firefox主浏览器窗口。
插件在控制台上有大量输出,因此您可以查看事情发生的顺序以及哪个插件可以接收哪些AddonManager
事件。控制台输出为[括号中是我对用户界面所做的操作以及一些注释]:
[User action: Start Firefox in installinfo@ex1 directory]
installinfo@ex1: In index.js
installinfo@ex1: In installAddonListener: Adding add-on listener
installinfo@ex1: Attaching content script A
installinfo@ex1: In exports.main: This add-on is being loaded for reason= install Object { loadReason: "install", staticArgs: undefined }
installinfo@ex1: Attaching content script B
installinfo@ex1: In exports.main: was passed callbacks= Object { print: print(), quit: function () }
[Note: no console.log output from within conentScriptA loading]
installinfo@ex1: received message from contentScriptA: Is Loaded
[Note: no console.log output from within conentScriptB loading]
installinfo@ex1: received message from contentScriptB: Is Loaded
[User action: Drag and drop .xpi for installinfo@ex2 onto Firefox]
installinfo@ex1: AddonManager Event: Installing addon ID: installinfo@ex2 ::needsRestart= false ::addon object: Object { }
installinfo@ex1: AddonManager Event: Installed addon ID: installinfo@ex2 ::addon object: Object { }
installinfo@ex2: In index.js
installinfo@ex2: In installAddonListener: Adding add-on listener
installinfo@ex2: Attaching content script A
installinfo@ex2: In exports.main: This add-on is being loaded for reason= install Object { loadReason: "install", staticArgs: undefined }
installinfo@ex2: Attaching content script B
installinfo@ex2: In exports.main: was passed callbacks= Object { print: print(_), quit: function () }
installinfo@ex2: In contentScriptA: Loaded
installinfo@ex2: received message from contentScriptA: Is Loaded
installinfo@ex2: In contentScriptB: Loaded
installinfo@ex2: received message from contentScriptB: Is Loaded
[User action: Navigate to about:addons]
[User action: Disable installinfo@ex2]
installinfo@ex1: AddonManager Event: Disabling addon ID: installinfo@ex2 ::needsRestart= false ::addon object: Object { }
installinfo@ex2: AddonManager Event: Disabling addon ID: installinfo@ex2 ::needsRestart= false ::addon object: Object { }
installinfo@ex2: In exports.onUnload: This add-on is being unloaded for reason= disable
installinfo@ex2: In removeAddonListener: Removing add-on listener
installinfo@ex1: AddonManager Event: Disabled addon ID: installinfo@ex2 ::addon object: Object { }
installinfo@ex2: AddonManager Event: Disabled addon ID: installinfo@ex2 ::addon object: Object { }
installinfo@ex1: AddonManager Event: Uninstalling addon ID: installinfo@ex2 ::needsRestart= true ::addon object: Object { }
[Get a warning in Browser Console because installinfo@ex2 did not remove its AddonManager listeners, and AddonManager is still trying to call them.]
1472563865661 addons.manager WARN AddonListener threw exception when calling onUninstalling: TypeError: can't access dead object (resource://gre/modules/AddonManager.jsm:1756:1) JS Stack trace: [email protected]:1756:1 < [email protected]:3075:5 < [email protected]:5041:7 < [email protected]:7484:5 < [email protected]:1548:13 < oncommand@about:addons:1:1
[User action: Refresh about:addons page to remove "undo" posibility for installinfo@ex2]
installinfo@ex1: Uninstalled addon ID: installinfo@ex2 ::addon object: Object { }
[Get a warning in Browser Console because installinfo@ex2 did not remove its AddonManager listeners, and AddonManager is still trying to call them.]
1472563873408 addons.manager WARN AddonListener threw exception when calling onUninstalled: TypeError: can't access dead object (resource://gre/modules/AddonManager.jsm:1756:1) JS Stack trace: [email protected]:1756:1 < [email protected]:3075:5 < [email protected]:5096:7 < [email protected]:7484:5 < [email protected]:1740:5 < [email protected]:2733:5 < [email protected]:651:7 < [email protected]:184:3 < EventListener.handleEvent*@extensions.js:84:1
[User action: Close main Firefox browser window]
[User action: Close Firefox Browser Console window]
(via dump):installinfo@ex1: In exports.onUnload: This add-on is being unloaded for reason= shutdown
我建议您尝试以下加载项,以了解AddonManager事件可能发生的事情以及代码在加载项中执行的时间。
附加文件:
index.js:
/* Firefox Add-on SDK test when code is executed upon install*/
//For testing:
var doNotRemoveAddonManagerListenersUponUninstall = true
var self = require("sdk/self");
var tabs = require("sdk/tabs");
var myId = self.id;
let myIdText = myId;
if(myId.indexOf('2') > -1){
//Indent console logs for version 2
myIdText = '\t\t' + myIdText ;
}
var utils = require('sdk/window/utils');
activeWin = utils.getMostRecentBrowserWindow();
//This will execute every time the add-on is loaded (e.g. install, startup, enable, etc).
myLog('In index.js');
//Open the Browser Console
activeWin.document.getElementById('menu_browserConsole').doCommand();
function myLog(){
// Using activeWin.console.log() is needed to have output to the
// Browser Console when installed as an .xpi file. In that case,
// console is mapped to dump(), which does not output to the console.
// This is done, I assume, to not polute the console from SDK add-ons
// that are logging information when they should not. Using jpm run,
// console.log outputs to the Browser Console.
let activeWin = require('sdk/window/utils').getMostRecentBrowserWindow();
// If Firefox is exiting (and some other conditions), there is
// no active window. At such times, we must use the version
// of console.log() aliases to dump().
let useConsole = console;
if(activeWin ){
//useConsole = activeWin.console;
}
useConsole.log(myIdText +':',...arguments);
}
function attachScript(script){
let tabWorker = tabs.activeTab.attach({
contentScriptFile: script,
contentScriptOptions: {
//extra \t because content script console.log (from .xpi) doesn't prefix with
// add-on name.
idText: '\t\t\t' + myIdText
}
});
tabWorker.port.on('consoleLog',logMessage);
return tabWorker;
}
function logMessage(message){
myLog(message);
}
exports.main = function (options,callbacks) {
myLog('In exports.main: This add-on is being loaded for reason=', options.loadReason
, options);
myLog('Attaching content script B');
attachScript('./contentScriptB.js');
if(typeof callbacks !== 'undefined'){
myLog('In exports.main: was passed callbacks=', callbacks);
}
switch (options.loadReason) {
case 'install':
//Do actions upon install
break;
case 'enable':
//Do actions upon enable
break;
case 'startup':
//Do actions upon startup
break;
case 'upgrade':
//Do actions upon upgrade
break;
case 'downgrade':
//Do actions upon downgrade
break;
default:
throw 'Unknown load reason:' + options.loadReason;
break; //Not needed, throw will exit
}
};
exports.onUnload = function (reason) {
myLog('In exports.onUnload: This add-on is being unloaded for reason=',reason);
//Your add-on listeners are NOT automatically removed when
// your add-on is disabled/uninstalled.
//You MUST remove them in exports.onUnload if the reason is
// not 'shutdown'. If you don't, errors will be shown in the
// console for all events for which you registered a listener.
if(reason !== 'shutdown') {
uninstallAddonListener();
}
};
const { AddonManager } = require("resource://gre/modules/AddonManager.jsm");
let addonListener = {
onEnabling: function(addon, needsRestart){
myLog('AddonManager Event: Enabliling addon ID: ' + addon.id
+ ' ::needsRestart= ' + needsRestart + ' ::addon object:', addon);
},
onEnabled: function(addon){
myLog('AddonManager Event: Enabled addon ID: ' + addon.id
+ ' ::addon object:', addon);
},
onDisabling: function(addon, needsRestart){
myLog('AddonManager Event: Disabling addon ID: ' + addon.id
+ ' ::needsRestart= ' + needsRestart + ' ::addon object:', addon);
},
onDisabled: function(addon){
myLog('AddonManager Event: Disabled addon ID: ' + addon.id
+ ' ::addon object:', addon);
},
onInstalling: function(addon, needsRestart){
myLog('AddonManager Event: Installing addon ID: ' + addon.id
+ ' ::needsRestart= ' + needsRestart + ' ::addon object:', addon);
},
onInstalled: function(addon){
myLog('AddonManager Event: Installed addon ID: ' + addon.id
+ ' ::addon object:', addon);
},
onUninstalling: function(addon, needsRestart){
myLog('AddonManager Event: Uninstalling addon ID: ' + addon.id
+ ' ::needsRestart= ' + needsRestart + ' ::addon object:', addon);
},
onUninstalled: function(addon){
myLog('AddonManager Event: Uninstalled addon ID: ' + addon.id
+ ' ::addon object:', addon);
},
onOperationCancelled: function(addon){
myLog('AddonManager Event: Add-on Operation Canceled addon ID: '
+ addon.id + ' ::addon object:', addon);
},
onPropertyChanged: function(addon, properties){
myLog('AddonManager Event: Add-on Property Changed addon ID: ' + addon.id
+ ' ::properties= ', properties, ' ::addon object:', addon);
}
}
function installAddonListener(){
//Using an AddonManager listener is not effective to listen for your own add-on's
// install event. The event happens prior to you adding the listener.
myLog('In installAddonListener: Adding add-on listener');
AddonManager.addAddonListener(addonListener);
}
function uninstallAddonListener(){
if(doNotRemoveAddonManagerListenersUponUninstall === true){
//Do the WRONG thing to demonstrate what happens when you don't
// remove AddonManager listeners upon your add-on being disabled.
return;
}
//Using an AddonManager listener is not effective to listen for your own add-on's
// install event. The event happens prior to you adding the listener.
myLog('In removeAddonListener: Removing add-on listener');
AddonManager.removeAddonListener(addonListener);
}
installAddonListener();
myLog('Attaching content script A');
attachScript('./contentScriptA.js');
数据/内容脚本A:
//console.log is ailiased to dump() when running under jpm run. Thus,
// you will not see the output from this line in the Browser Console
// when run under jpm run. It will appear in the console window from
// which you executed 'jpm run'
// From an .xpi it outputs to the Browser Console, as expected.
console.log(self.options.idText + ': In contentScriptA: Loaded');
//Send a message to the background script that this content script is loaded.
self.port.emit('consoleLog', 'received message from contentScriptA: Is Loaded');
数据/ contentScriptB:
//console.log is ailiased to dump() when running under jpm run. Thus,
// you will not see the output from this line in the Browser Console
// when run under jpm run. It will appear in the console window from
// which you executed 'jpm run'
// From an .xpi it outputs to the Browser Console, as expected.
console.log(self.options.idText + ': In contentScriptB: Loaded');
//Send a message to the background script that this content script is loaded.
self.port.emit('consoleLog', 'received message from contentScriptB: Is Loaded');
package.json(用于installinfo @ ex1):
{
"title": "Demo when code executes re install 1",
"name": "installinfo1",
"id": "installinfo@ex1",
"version": "0.0.1",
"description": "Demo when execute various code with respect to install",
"main": "index.js",
"author": "Makyen",
"engines": {
"firefox": ">=38.0a1",
"fennec": ">=38.0a1"
},
"license": "MIT",
"keywords": [
"jetpack"
]
}
package.json(用于installinfo @ ex2):
{
"title": "Demo when code executes re install 2",
"name": "installinfo2",
"id": "installinfo@ex2",
"version": "0.0.1",
"description": "Demo when execute various code with respect to install",
"main": "index.js",
"author": "Makyen",
"engines": {
"firefox": ">=38.0a1",
"fennec": ">=38.0a1"
},
"license": "MIT",
"keywords": [
"jetpack"
]
}
关于javascript - 在Firefox附加SDK扩展中的“onInstalled”上执行脚本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39190574/