我对mozilla扩展开发很新,甚至我刚刚了解扩展和附加开发是不同的 我对MDN(Mozilla开发者网络)的看法非常感兴趣 我想在我的附加组件安装完成后执行脚本'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扩展不是附加组件时,我正在尝试使用它,因为它给了我错误浏览器undefined和chrome.runtime未定义
然后我在AddonManager.addAddonListener()中找到onInstalled() https://developer.mozilla.org/en-US/Add-ons/Add-on_Manager/AddonListener#onInstalled()
但我仍然感到困惑,我应该如何在我的附加组件中使用它
我试过的方式是给我错误
//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 addon没有任何想法。我甚至无法达到“已安装”,执行content_script远远不够远 如果有人知道怎么做,请帮助。
提前致谢
答案 0 :(得分:2)
看来你遇到了一些问题:
tabs.executeScript()
方法{}正在寻找tab.attach()
。对于有效标签,它将是tabs.activeTab.attach()
。AddonManager
onInstalled
事件发生在之前到正在运行的加载项的任何代码。因此,您不会收到正在侦听的加载项的此事件。
AddonManager
主要用于您的加载项,以便能够监控涉及其他加载项的活动。它在监视用于监视的附加组件活动方面的用处是有限的。AddonManager
onDisabled
事件。如果用户直接删除它,您只会收到onUninstalling
事件。console.log()
未显示在浏览器控制台中的问题用jpm run
测试。输出在控制台窗口中可用,该窗口执行jpm run
。虽然按设计将输出转到控制台窗口,但我觉得输出不会输出到浏览器控制台(除控制台窗口之外)是错误或错误。about:*
页面会导致某些行为与将其加载到普通网页不同。此行为可能包括使console.log()
输出仅显示为使用dump()
输出(即它不会显示在浏览器控制台中,但会在执行Firefox / {{1}的控制台中显示})。如果您尝试这样做,则需要尝试一下您可以做的事情。jpm run
输出的正确位置Browser Console。因此,我在下面的附加组件中自动打开浏览器控制台。
"main"
中指定的JavaScript文件会运行。它也可以在Firefox启动时运行。exports.main
函数,该函数会在评估并执行console.log()
JavaScript文件中的代码后自动调用。此函数可用于查找正在执行加载项的原因。可能的原因有"main"
,install
,enable
,startup
和upgrade
。下面的附加组件演示了何时执行此代码并将downgrade
传递给它。为了演示各种各样的东西,我编写了一个Firefox Add-on SDK扩展,它可以加载一些内容脚本并监听reason
个事件。我制作了这个附加组件的两个版本,这些版本只在名称和ID上有所不同,这些名称和ID分别分配给各自的 package.json 文件。这两个加载项是AddonManager
和installinfo@ex1
。
第一个加载项installinfo@ex2
是通过在其目录中运行installinfo@ex1
加载的。第二个加载项jpm run
是通过拖放installinfo@ex2
为其创建的 .xpi 来安装的。使用Firefox UI,我立即导航到jpm xpi
( Ctrl - Shift - A , Cmd - OSX上的 Shift - A 并继续先禁用about:addons
;那么"删除" installinfo@ex2
;然后刷新installinfo@ex2
页面,使其无法撤消"撤消"删除。然后我退出Firefox主浏览器窗口。
附加组件对控制台有大量输出,因此您可以查看事件发生的顺序以及哪个附加组件能够接收哪些about:addons
个事件。控制台输出[在括号中标注我正在使用的用户界面和一些注释]:
AddonManager
我建议你试验下面的附加组件,以了解AddonManager事件的可能性以及代码在附加组件中执行的时间。
附加文件:
index.js :
[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: AddonManagerInternal.callAddonListeners@AddonManager.jsm:1756:1 < this.AddonManagerPrivate.callAddonListeners@AddonManager.jsm:3075:5 < this.XPIProvider.uninstallAddon@XPIProvider.jsm:5041:7 < AddonWrapper.prototype.uninstall@XPIProvider.jsm:7484:5 < uninstall@extensions.xml: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: AddonManagerInternal.callAddonListeners@AddonManager.jsm:1756:1 < this.AddonManagerPrivate.callAddonListeners@AddonManager.jsm:3075:5 < this.XPIProvider.uninstallAddon@XPIProvider.jsm:5096:7 < AddonWrapper.prototype.uninstall@XPIProvider.jsm:7484:5 < doPendingUninstalls@extensions.js:1740:5 < gListView.hide@extensions.js:2733:5 < gViewController.shutdown@extensions.js:651:7 < shutdown@extensions.js: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
数据/ contentScriptA :
/* 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');
数据/ 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 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');
package.json (对于installinfo @ ex1):
//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 @ ex2):
{
"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"
]
}