【问题标题】:Replaceing/swapping JavaScript file in html using Greasemonkey使用 Greasemonkey 替换/交换 html 中的 JavaScript 文件
【发布时间】:2017-04-17 03:40:06
【问题描述】:

我的目标是用我在本地拥有的自制文件替换网页中的原始 JavaScript 文件。我找到了一个有趣的脚本here,我将其重新用于我的目标。

// ==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) 脚本的某种错误。

输出:

//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(或其他扩展程序)解决这个问题的另一种方法?

如果您对某些涉及的文件感兴趣,我已经创建了另一个 thread 与同一个项目的另一个(不同)问题。

【问题讨论】:

    标签: javascript greasemonkey http-proxy tampermonkey


    【解决方案1】:

    原来的脚本在injectScript之前已经执行过了,所以即使你的tampermonkey按预期工作,结果也可能不是你需要的。通常,您需要一个代理服务器来实现这一点。

    如果您不想构建代理服务器,请尝试在原始脚本中找到if(window.a)return; 之类的内容,在您的tampermoneky 脚本中写入window.a=true,在document-startinsert your own script 运行它

    【讨论】:

    • 感谢您的回答!我应该用一些东西替换来自window.a 吗?
    • @Clone 这只是一个例子。这取决于 oldJSFile 的内容。你甚至可以覆盖一些原生 api 来引发错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 2016-05-03
    • 2012-11-12
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    相关资源
    最近更新 更多