使用Greasemonkey删除javascript函数

时间:2013-03-07 22:07:32

标签: javascript function greasemonkey

我在HTML的头部访问了一个带有javascript文件的网站

<script language="javascript" src="javscript.js"></script>

此文件中的代码是:

// keypress management 
if (document.layers) document.captureEvents(Event.KEYPRESS)
function update(e) {        
    if (document.all) {             // Explorer
        if (event.keyCode==13) document.forms[0].submit();  // 13 = ENTER
        else if (event.keyCode==26) runHelp(hplk);          // 26 = CTRL+Z
        return;
    } else {                                                // mozilla
        if (e.which==13) document.forms[0].submit();        // 13 = ENTER
        else if (e.which==26) runHelp(hplk);                // 122 = CTRL+Z     
        return;         
    }
}
document.onkeypress=update;

我想用Greasemonkey禁用/删除/替换此功能。

我用

尝试了
unsafeWindow.update = function(){}

没有结果! (在控制台中没有错误)

有没有办法杀死这个功能?

1 个答案:

答案 0 :(得分:8)

update是一个全局函数尚不清楚。如果不是,那么这种方法将无效。

但你可以用:

覆盖按键处理程序
unsafeWindow.document.onkeypress = function(){};



对于选择性阻止或替换任何JS(在Firefox上)的通用,高效方式,请使用@run-at document-startthe checkForBadJavascripts function,如下所示:

// ==UserScript==
// @name        _Replace select javascript on a page
// @include     http://YOUR_SERVER.COM/YOUR_PATH/*
// @require     https://gist.github.com/raw/2620135/checkForBadJavascripts.js
// @run-at      document-start
// @grant       GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

checkForBadJavascripts ( [
    [   false,
        /document\.onkeypress\s*=\s*update/,
        function () {
            addJS_Node (myKeypressFunction.toString() );
            addJS_Node ('document.onkeypress = myKeypressFunction;');
        }
    ]
] );


function myKeypressFunction (evt) {
    /*  DO WHATEVER HERE BUT USE NO GREASEMONKEY FUNCTIONS INSIDE
        THIS FUNCTION.
    */
    console.log ("Keypress function fired.");
}

See this answer, for more information on checkForBadJavascripts.