This works splendidly with the new Greasemonkey @run-at directive!
Here is an example userscript:
http://userscripts.org/scripts/show/125936
Important quote:
This user script will run right at the document beginning, as for
Scriptish, it even runs before getting any HTTP response ( which is
excellent for redirecting ).
It shows how to remove malicious JS from a website.
Here is the full script example:
// ==UserScript==
// @name editscript
// @version 0.0.1
// @namespace example@example.com
// @include http://*
// @run-at document-start
// ==/UserScript==
var changed = 0; // script need to be edited with
window.addEventListener('beforescriptexecute', function(e) {
///for external script:
src = e.target.src;
if (src.search(/bad\.js/) != -1) {
changed++;
e.preventDefault();
e.stopPropagation();
append(NewScript1);
};
///for inline script:
if(e.target===document.getElementsByTagName("script")[0]){
changed++;
e.stopPropagation();
e.preventDefault();
//todo
}
//tips: you could also run a regex search for the e.target.innerHTML
//if the position of the inline script is not fixed.
///when done, remove the listener:
if(changed == 2) window.removeEventListener(e.type, arguments.callee, true);
}, true);
////// append with new block function:
function append(s) {
document.head.appendChild(document.createElement('script'))
.innerHTML = s.toString().replace(/^function.*{|}$/g, '');
}
////////////////////////////////////////////////
function NewScript1(){
/* insert new block here, like: */
function load_good_stuff(){
/* we still got it!!
* only without the evil thing.
*/
}
};