2017-04-17 15 views
0

私の目標は、私がローカルに持っている自家製のファイルでWebページの元の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); 

しかし、コンソールログには、エラーのための開口部(document.open())ファイルまたは交換(.replace)スクリプトのいくつかの種類におそらくステージ3に達することはありません。

出力:私はこの問題やグリースモンキー(またはその他の拡張子)を使用してこの問題を解決する、おそらく別の方法を持っていますなぜ

//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" 

は誰もが知っていますか?

私は、関連するファイルのいくつかに興味がある場合、別の(別の)質問を同じプロジェクトで作成しました。

答えて

1

元のスクリプトはすでにinjectScriptより前に実行されていました。したがって、あなたのタンパーキーが期待通りに機能しても、結果は必要なものにならないことがあります。一般的に、これを実現するにはプロキシサーバーが必要です。

プロキシサーバーを構築したくない場合は、お使いのtampermonekyスクリプトでwindow.a=trueを書き、元のスクリプトにif(window.a)return;のようなものを見つけようと、document-startでそれを実行し、insert your own script

+0

は、あなたの答えをありがとう!私は 'window.a'から何かに置き換えるべきですか? – Clone

+0

@Cloneこれは単なる例です。これは 'oldJSFile'の内容に依存します。いくつかのネイティブAPIをオーバーライドしてエラーを発生させることさえできます。 – blackmiaool

関連する問題