由于页面使用$.get(),因此拦截请求更加容易。使用ajaxSuccess()。
这将在 Greasemonkey(Firefox) 脚本中运行:
片段 1:
unsafeWindow.$('body').ajaxSuccess (
function (event, requestData)
{
console.log (requestData.responseText);
}
);
假设页面以正常方式使用 jQuery($ 已定义等)。
这应该适用于 Chrome 用户脚本(以及 Greasemonkey):
片段 2:
function interceptAjax () {
$('body').ajaxSuccess (
function (event, requestData)
{
console.log (requestData.responseText);
}
);
}
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, interceptAjax);
回复:
“但是我如何将这些数据获取到脚本中?...(这样我可以)稍后在脚本中使用这些数据。”
这适用于 Greasemonkey(Firefox);它也可能适用于 Chrome 的 Tampermonkey:
Snippet 3:
function myAjaxHandler (requestData) {
console.log ('myAjaxHandler: ', requestData.responseText);
}
unsafeWindow.$('body').ajaxSuccess (
function (event, requestData) {
myAjaxHandler (requestData);
}
);
但是,如果不这样做,那么您将无法(轻松地)在 Chrome 用户脚本和目标页面之间共享 JS 信息——这是设计使然。
通常您所做的是注入整个用户脚本,以便所有内容都在页面范围内运行。像这样:
片段 4:
function scriptWrapper () {
//--- Intercept Ajax
$('body').ajaxSuccess (
function (event, requestData) {
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);