2013-09-28 65 views
0

有一個網站我用一些強大的罰款JavaScript寫的。幾乎沒有任何全局變量,無處不在,它使用嚴格模式。這使我很難將自己的功能注入到網站中。如何從Greasemonkey腳本中替換,移除或攔截jQuery的ready事件?

網站客戶端對象初始化一個jQuery.ready()電話:

$(window).ready(function() { 
    var a, b, c, d; 

    // Setup global data [...] 
    // Setup configuration [...] 

    a = GlobalFoo.ConstructorA(); 
    b = GlobalFoo.ConstructorB(a); 
    // Really wish I could put stuff here 
    c = GlobalFoo.ConstructorC(a, b); 
    d = GlobalFoo.ConstructorD(b, c); 
    // etc. 
}); 

如何我舉個例子,用我自己的代碼替換​​被稱爲其他構造之前?

我可以停止發生就緒事件嗎?或者用我自己的代碼替換它?由於它非常小,我只能在我的代碼中複製修改後的版本。

+0

可能重複。 com/questions/10472569/changed-javascript-on-html-page-out-of-my-control) –

回答

2

經過多一點搜索,我發現this wonderful page由dindog。在GreaseSpot wiki上也有this page描述@run-at

@run-at允許您的腳本在所有其他代碼之前運行。 beforescriptexecute事件允許您在執行每個腳本之前檢查它們。然後您可以跳過或修改它。

我最終的解決方案是:

// ==UserScript== 
// @name  ... 
// @description ... 
// @namespace ... 
// @include  ... 
// @version  1 
// @run-at  document-start 
// @grant  none 
// ==/UserScript== 

(function (w) { 
    // Remove the current jQuery ready code 
    function pre_script_execute_handler (e) { 
     var target = e.target; 
     if (target.innerHTML.indexOf("$(window).ready(") != -1) { 
      console.log('Removed ready'); 
      e.preventDefault(); 
      e.stopPropagation(); 
      addReady(); 
     } 
    } 
    w.addEventListener('beforescriptexecute', pre_script_execute_handler); 

    // Add new jQuery ready code 
    function addReady() { 
     console.log('Adding new ready'); 
     w.$(window).ready(function() { 
      console.log('Our ready called'); 
     }); 
    } 


}) (unsafeWindow); 
+0

@BrockAdams我搜索到了谷歌,但沒有注意到該帖子。由於問題標題非常模糊,我可能會忽略它。由於代碼結構顯得非常不同,我不會說dindog的帖子是從你的SO帖子派生的。 – Annan

+0

我沒有說他的帖子是從我的。但從其他信息上。但是,由於我無法證明這一點,我收回了我的陳述。 –

0

在一般情況下,手術禁用或改變頁面的JavaScript,使用checkForBadJavascripts如圖"How to alter this javascript with Greasemonkey?"。 (注意,這僅僅是Firefox的還有在Chrome中做到這一點沒有什麼好辦法)

在這種情況下,你的腳本會是這樣:

// ==UserScript== 
// @name  _Replace page's ready function 
// @include http://YOUR_SERVER.COM/YOUR_PATH/* 
// @require https://gist.github.com/raw/2620135/checkForBadJavascripts.js 
// @run-at document-start 
// @grant GM_addStyle 
// ==/UserScript== 
/*- The @grant directive is needed to work around a design change 
    introduced in GM 1.0. It restores the sandbox. 
*/ 
console.log ("Script run"); 
checkForBadJavascripts ([ 
    [ false, 
     /\$\(window\)\.ready\b/, 
     function() { addJS_Node (null, null, addBetterReady); } 
    ] 
]); 

function addBetterReady() { 
    //-- The space before "ready" is CRUCIAL to avoid recursion. 
    $(window). ready (function() { 
     // YOUR READY CODE HERE. 
    }); 
} 


...假設直列JavaScript的。

如果ready函數在一個外部文件中,checkForBadJavascripts電話更改爲類似://計算器:在HTML頁面中的JavaScript更改了我的控制(HTTP的

checkForBadJavascripts ([ 
    [ true, 
     /unwantedFilename\.js/, 
     function() { addJS_Node (null, null, addBetterReady); } 
    ] 
]);