使用Greasemonkey替换/交换html中的JavaScript文件 [英] Replaceing/swapping JavaScript file in html using Greasemonkey
问题描述
我的目标是使用我在本地拥有的自制文件从网页替换原始JavaScript文件。我找到了一个有趣的脚本这里,我重新调整以符合我的目标。
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);
但控制台日志从未到达阶段3,可能是由于某种错误打开( document.open()
)文件或替换( .replace
)脚本。
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.
输出:
//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"
有谁知道为什么我遇到这个问题或者使用Greasemonkey(或其他扩展程序)解决这个问题的其他方法?
我创建了另一个线程如果您对某些涉及的文件感兴趣,可以在同一个项目上使用另一个(不同的)问题。
I have created another thread with another (different) question on the same project if you are interested in some of the involved files.
推荐答案
原始脚本已在 injectScript
之前执行,所以,即使您的防篡改按预期工作,结果可能也不像您需要的那样。通常,您需要一个代理服务器来实现此目的。
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(window.a)return;
在原始脚本中,在你的tampermoneky脚本中写 window.a = true
,在 document-start ,插入自己的脚本
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
这篇关于使用Greasemonkey替换/交换html中的JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!