userscript ajax,ajax - capture a pages xmlhttp requests with a userscript - Stack Overflow

Since the page uses $.get(), it's even easier to intercept requests. Use ajaxSuccess().

This will work in a Greasemonkey(Firefox) script:

Snippet 1:

unsafeWindow.$('body').ajaxSuccess (

function (event, requestData)

{

console.log (requestData.responseText);

}

);

Assuming the page uses jQuery in the normal way ($ is defined, etc.).

This should work in a Chrome userscript (as well as Greasemonkey):

Snippet 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);

Re:

"But how then do I get that data to the script? ... (So I can) use the data later in the script."

This works in Greasemonkey(Firefox); it might also work in Chrome's Tampermonkey:

Snippet 3:

function myAjaxHandler (requestData) {

console.log ('myAjaxHandler: ', requestData.responseText);

}

unsafeWindow.$('body').ajaxSuccess (

function (event, requestData) {

myAjaxHandler (requestData);

}

);

But, if it doesn't then you cannot share JS information (easily) between a Chrome userscript and the target page -- by design.

Typically what you do is inject your entire userscript, so that everything runs in the page scope. Like so:

Snippet 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值