【发布时间】:2014-06-26 22:42:58
【问题描述】:
我正在编写一个密码管理器,我的扩展程序在页面准备好时创建了一个监听器,所以在导航了几个 url 之后,我就有了一堆监听器。我想响应用户单击“提交”表单按钮而一次没有多个侦听器处于活动状态,因此我想分离内容脚本。
现在它侦听表单提交,然后检查加载的下一页是否存在“密码错误”等,然后执行其他一些操作。这是我附加监听器的代码:
tabs.on("ready", function(tab) {
fillLoginAndPass(tab);
listenForLoginSubmit(tab);
});
function listenForLoginSubmit(tab) {
// attach submit listener
worker = tab.attach({
contentScriptFile: [data.url("jquery-1.11.1.min.js"), data.url("listener-script.js")]
});
worker.port.on("submittedCredentials", function (formSubmitURL, enteredLogin, loginField, enteredPassword, passwordField) {
tab.on("ready", function() {
checkLogin(tab, formSubmitURL, enteredLogin, loginField, enteredPassword, passwordField);
});
});
}
我尝试过使用 worker.destroy(),但没有任何效果 - port.on() 脚本仍会执行多次。还有另一种方法吗?提前致谢。
编辑
为了澄清,这就是我的代码在 worker.destroy() 中的样子:
function listenForLoginSubmit(tab) {
// attach submit listener
worker = tab.attach({
contentScriptFile: [data.url("jquery-1.11.1.min.js"), data.url("listener-script.js")]
});
worker.on("detach", function() {
console.log("Worker detached from "+tabs.activeTab.url);
});
worker.port.on("submittedCredentials", function (formSubmitURL, enteredLogin, loginField, enteredPassword, passwordField) {
tab.on("ready", function() {
checkLogin(tab, formSubmitURL, enteredLogin, loginField, enteredPassword, passwordField);
worker.destroy();
});
});
}
function checkLogin(tab, formSubmitURL, enteredLogin, loginField, enteredPassword, passwordField) {
console.log("Hello!");
/* code */
}
而输出的区别是:
// without worker.destroy()
/* Log in to wikipedia.org */
console.log: passman: Hello!
/* Log out, return to login page */
/* Log in a second time */
console.log: passman: Hello!
console.log: passman: Hello!
console.log: passman: Worker detached from https://en.wikipedia.org/w/index.php?title=Special:Search&search=&go=Go
// with worker.destroy()
/* Log in to wikipedia.org */
console.log: passman: Hello!
console.log: passman: Worker detached from https://en.wikipedia.org/w/index.php?title=Special:Search&search=&go=Go
/* Log out, return to login page */
/* Log in a second time */
console.log: passman: Hello!
console.log: passman: Worker detached from https://en.wikipedia.org/w/index.php?title=Special:Search&search=&go=Go
console.log: passman: Hello!
console.log: passman: Worker detached from https://en.wikipedia.org/w/index.php?title=Special:Search&search=&go=Go
如果我第三次这样做,我会得到 3 个“Hello!”,以此类推。再次感谢您提供的任何帮助。
编辑 2 cmets 中的错误报告 Zer0 链接有答案。这里是:
let { off } = require("sdk/event/core");
off(worker.port);
【问题讨论】:
-
这很奇怪;
worker.destroy应该有一些效果。我提交了以下bug。 -
尝试阅读这个主题可能会有所帮助,也许,我不确定。 :stackoverflow.com/questions/22382201/…
-
感谢 ZER0 创建错误报告。澄清一下,worker.destroy() 确实激活了 onDetach: 函数,但没有删除 contentscript。我已经编辑了我的问题以包含它。 @Noitidart:谢谢。不幸的是,这并没有奏效。它似乎已经附加到页面顶部,每个页面加载只有一次。我正在加载多个页面的事实导致它堆积起来。
标签: ajax sdk firefox-addon mozilla firefox-addon-sdk