2017-04-17 179 views
0

我的目標是用本地擁有的自制文件替換網頁中的原始JavaScript文件。我找到了一個有趣的腳本here,我用它來適應我的目標。使用Greasemonkey替換/交換html文件中的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的(或其它擴展名)這個問題也許是另一種方式?

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

回答

1

原始腳本已經在injectScript之前執行過,所以即使您的防篡改按鈕按預期工作,結果可能並不像您所需要的那樣。一般來說,你需要一個代理服務器來實現這一點。

如果你不希望建立一個代理服務器,試圖找到像在原來的劇本if(window.a)return;,在你的tampermoneky腳本編寫window.a=true,它運行在document-start,並insert your own script

+0

謝謝您的回答!我應該用'window.a'替換一個東西嗎? – Clone

+0

@Clone這只是一個例子。這取決於'oldJSFile'的內容。你甚至可以重寫一些本地API來提出一個錯誤。 – blackmiaool