Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a javascript function with Greasemonkey

I visit a website with a javascript file in the head of the HTML

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

The code inside this file is:

// 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;

I want to disable/remove/replace this function with Greasemonkey.

I tried it with

unsafeWindow.update = function(){}

with no result! (got no errors in the console)

is there a way to kill this function?

like image 287
bernte Avatar asked Mar 07 '13 22:03

bernte


1 Answers

It's not clear that update is a global function. If it isn't then that approach won't work.

But you can override the keypress handler with:

unsafeWindow.document.onkeypress = function(){};



For a general, high-powered way to selectively block, or replace, any JS (on Firefox), use @run-at document-start and the checkForBadJavascripts function, like so:

// ==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.

like image 59
Brock Adams Avatar answered Oct 07 '22 02:10

Brock Adams