我有一个如下所示的基本防油精脚本,其中我希望每次运行脚本的网站发送AJAX请求时都运行一些代码。
我正在使用ajaxSuccess jQuery处理程序,它没有被解雇。我怀疑这可能是因为AJAX请求发送时全局标志设置为false(请参阅http://docs.jquery.com/Ajax_Events)。有没有更好的方法来实现这一点,即使在global设置为false的情况下也能奏效?
代码:
// ==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)Inject脚本。
(A) 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范围——小心将两者混合。
在这个答案中可以找到一种变通方法,用于在沙箱中传输数据。
这可能与防油精沙盒有关。
http://greasemonkey.mozdev.org/authoring.html
有时,您会想要访问内容文档中的全局变量。例如,内容文档可能定义了要调用的函数。在这些情况下,您可以使用unsafeWindow变量访问内容文档的全局作用域。请注意,访问此变量的成员意味着内容脚本可以检测到您的脚本,如果他们选择,可能会干扰脚本
例如,防油精脚本中的document
可能与实际网页中的document
不同,因此您可能必须使用unsafeWindow.document
或其他内容。
或者,jQuery的ajax方法在不进行更改的情况下(需要特殊的XHR对象覆盖)根本无法在防油麦中工作。。。
例如。http://www.monperrus.net/martin/greasemonkey+jquery+和+xmlhttprequest+一起
以及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){
....
}
});