使用Greasemonkey脚本删除MooTools事件



我正在尝试修改一个使用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工具实例必须是删除事件的那个。

最新更新