Old question, but I needed to do this recently. Here's how I did it using GreaseMonkey.
You add the beforescriptexecute listener, and wait for your target script to be loaded, checking the src tag to identify the correct script.
Then you stop that script from loading and get the script source yourself using GM_xmlhttpRequest.
Then you are free to modify the script as you please and insert it back into the DOM.
// ==UserScript==
// @name Test
// @namespace Test
// @description TEST
// @include http://the.website.com/*
// @version 1
// @grant GM_xmlhttpRequest
// @run-at document-start
// ==/UserScript==
function addScript(text) {
text = text.replace(/replaceThis();/g, "");
var newScript = document.createElement('script');
newScript.type = "text/javascript";
newScript.textContent = text;
var head = document.getElementsByTagName('head')[0];
head.appendChild(newScript);
}
window.addEventListener('beforescriptexecute', function(e) {
src = e.target.src;
if (src.search(/script_to_modify\.js/) != -1) {
e.preventDefault();
e.stopPropagation();
GM_xmlhttpRequest({
method: "GET",
url: e.target.src,
onload: function(response) {
addScript(response.responseText);
}
});
}
});