簡體   English   中英

為什么我的ajaxSuccess jQuery事件沒有在Greasemonkey中被觸發?

[英]Why is my ajaxSuccess jQuery event not being fired in Greasemonkey?

我有一個基本的greasemonkey腳本,如下所示,我想在每次運行腳本的網站發送AJAX請求時運行一些代碼。

我正在使用ajaxSuccess jQuery處理程序,它沒有被觸發。 我懷疑這可能是因為AJAX請求是在全局標志設置為false的情況下發送的(請參閱http://docs.jquery.com/Ajax_Events )。 有沒有更好的方法來實現這一點,即使全局被設置為假也會有效?

碼:

// ==UserScript==
// @name           MyTestScript
// @require        http://code.jquery.com/jquery-1.7.1.min.js
// @namespace      NRA
// @include        http://www.mysamplewebsite.com/view/*
// ==/UserScript==

$(document).ajaxSuccess(function(e, xhr) {
    alert("ajax success hit!");
    // I will do my other handling here
});

謝謝

用戶腳本中的jQuery在與頁面jQuery不同的環境中運行

您需要攔截頁面的 AJAX調用,以便可以使用(A) unsafeWindow或(B)注入腳本。

(一) unsafeWindow看起來像:

unsafeWindow.$(document).ajaxSuccess(function(e, xhr) {
    alert("ajax success hit!");
    // I will do my other handling here
});


(B)腳本注入看起來像:

function scriptWrapper () {

    //--- Intercept Ajax
    $('body').ajaxSuccess (
        function (event, requestData) {
            alert ("ajax success hit!");
            doStuffWithAjax (requestData);
        }
    );

    function doStuffWithAjax (requestData) {
        console.log ('doStuffWithAjax: ', requestData.responseText);
    }

    //--- DO YOUR OTHER STUFF HERE.
    console.log ('Doing stuff outside Ajax.');
}

function addJS_Node (text, s_URL, funcToRun) {
    var D                                   = document;
    var scriptNode                          = D.createElement ('script');
    scriptNode.type                         = "text/javascript";
    if (text)       scriptNode.textContent  = text;
    if (s_URL)      scriptNode.src          = s_URL;
    if (funcToRun)  scriptNode.textContent  = '(' + funcToRun.toString() + ')()';

    var targ    = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
    targ.appendChild (scriptNode);
}

addJS_Node (null, null, scriptWrapper);


請注意,在這兩種情況下,您都必須意識到數據不會輕易地從頁面范圍流回GM范圍-小心地將兩者混合

這個答案中可以找到一種解決方法,用於在沙箱中傳輸數據。

它可能與greasemonkey沙盒有關。

http://greasemonkey.mozdev.org/authoring.html

有時,您需要訪問內容文檔中的全局變量。 例如,內容文檔可能定義了您要調用的函數。 在這些情況下,您可以使用unsafeWindow變量訪問內容文檔的全局范圍。 請注意,訪問此變量的成員意味着內容腳本可以檢測到您的腳本,如果他們選擇,可能會干擾它。

即,油脂猴子腳本中的document可能與實際網頁中的document ,因此您可能必須使用unsafeWindow.document或其他內容。

或者也許jQuery的ajax方法根本不能在greasemonkey中工作而不需要改動(需要特殊覆蓋XHR對象)......

例如http://www.monperrus.net/martin/greasemonkey+jquery+and+xmlhttprequest+together

http://ryangreenberg.com/archives/2010/03/greasemonkey_jquery.php

... Greasemonkey中的JQuery AJAX如下所示:

$.ajax({
  url: '/p/',// this even works for cross-domain requests by default
  xhr: function(){return new GM_XHR();},
  type: 'POST',
  success: function(val){
  .... 
  }
});

暫無
暫無

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

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