簡體   English   中英

使用Greasemonkey替換/交換html中的JavaScript文件

[英]Replaceing/swapping JavaScript file in html using Greasemonkey

我的目標是將網頁中的原始JavaScript文件替換為本地擁有的自制文件。 我在這里找到了一個有趣的腳本,我將其重新調整為適合我的目標。

// ==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(或其他擴展名)解決該問題的另一種方式?

如果您對某些涉及的文件感興趣,我已經在同一項目上創建了另一個線程 ,另一個問題(不同)。

原始腳本已經在injectScript之前執行過,因此即使您的tampermonkey可以按預期工作,結果也可能與您所需的不一樣。 通常,您需要代理服務器來實現此目的。

如果您不想構建代理服務器,請嘗試查找類似if(window.a)return; 在原始腳本中,在您的tampermoneky腳本中編寫window.a=true ,在document-start上運行它,然后插入您自己的腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM