我正在尝试修改使用MooTools的页面,以便将事件监听器添加到某些字段,例如:
$('inputPassword').addEvents({
keypress: function(){
new WorkspaceModalbox({'href':'someurl.phtml', 'width':500, 'height':140, 'title':'foo'});
}
});
我需要使用Greasemonkey / Tampermonkey删除此行为。我尝试过:
// ==UserScript==
// @require http://userscripts.org/scripts/source/44063.user.js
// ==/UserScript==
window.addEventListener("load", function(e) {
$('inputPassword').removeEvents('keypress');
}, false);
其中removeEvents
是MooTools提供的功能,与addEvents
相反。
但是该脚本不起作用。 (编者注:没有报告的错误)
为什么?是因为我的代码在实际页面中的代码之前执行了吗?
该事件已安装在页面范围内,但脚本正在脚本范围内运行。另外,取决于浏览器和@grant
设置,可能涉及一个沙箱。
因此,要删除该事件,您必须使用脚本注入(Moo工具在unsafeWindow
上看起来效果不佳。)
此脚本可同时用于Greasemonkey和Tampermonkey:
// ==UserScript==
// @name _Remove a Moo event listener
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
window.addEventListener ("load", function (e) {
addJS_Node ("$('inputPassword').removeEvents('keypress');");
}, false);
//-- addJS_Node is a standard(ish) function
function addJS_Node (text, s_URL, funcToRun, runOnLoad) {
var D = document;
var scriptNode = D.createElement ('script');
if (runOnLoad) {
scriptNode.addEventListener ("load", runOnLoad, false);
}
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
targ.appendChild (scriptNode);
}
请注意,无需为此而仅在Moo工具中插入@require
,因为Moo工具的页面实例必须是删除事件的实例。