问题
My goal is to replace an original JavaScript file from a web-page with my home-made file that I have locally. I have found an interesting script here which I repurposed to fit my objective.
// ==UserScript==
// @name JS_tamper
// @namespace namespace
// @include http://192.168.1.1/*
// @version 1
// @grant none
// @run-at document-start
// ==/UserScript==
var newJSFile = "http://localhost:8080/tamper.js"; //The JS file to load in replacment of old JS file
var oldJSFile = "http://192.168.1.1/menuBcm.js"; //The old JS file as it is named in inspect element (make sure its spelled EXACTLY the same)
var pattern = new RegExp(oldJSFile, "i"); //Create the RegExp pattern with the /i switch to make it case-insensitive
function injectScript(originalPage) { //Function injectScript replaces the file
console.log('Replace stage 2: Replace text matching', oldJSFile, 'with', newJSFile);
var moddedPage = originalPage.replace(pattern, newJSFile); //Modify the HTML code that we got, replacing the old JS file with the new one
document.open();
console.log('Replace stage 3: Write new HTML to page...');
document.write(moddedPage); //Write to the page the new HTML code
document.close();
}
setTimeout(function() { //Wait a bit for the page's HTML to load...
console.log('Replace stage 1: target HTML');
injectScript(document.documentElement.outerHTML); //Run function injectScript with the page's HTML as oldPage in the function
}, 1111);
But the console log never reaches stage 3 presumably due to some kind of error opening ( document.open()
) the file or replacing ( .replace
) the script.
Output:
//Replace stage 1: target HTML JS_tamper.user.js:29:5
//Replace stage 2: Replace text matching "http://192.168.1.1/menuBcm.js" with "http://localhost:8080/tamper.js"
Does anyone know why I am having this issue or perhaps another way of solving this problem using Greasemonkey(or other extension)?
I have created another thread with another (different) question on the same project if you are interested in some of the involved files.
回答1:
The original script was already executed before the injectScript
, so even if your tampermonkey works as expected, the result may not be like what you need. Generally,You need a proxy server to achieve this.
If you don't want to build a proxy server, try to find something like if(window.a)return;
in the original script, write window.a=true
in your tampermoneky script, runs it at document-start, and insert your own script
来源:https://stackoverflow.com/questions/43444796/replaceing-swapping-javascript-file-in-html-using-greasemonkey