c global 拦截 ajax,Ajax-hook: :trident: Global Ajax interception, hook XMLHttpRequest, intercept ajax ...

Ajax-Hook是一个用于JavaScript全局XMLHttpRequest对象的库,它可以让你钩取并改变默认的Ajax请求和响应。通过安装和调用ajax-hook,你可以自定义回调函数,如onreadystatechange和onload,以及open等方法。例如,你可以中断GET请求,或者修改'responseText'。这个库对于调试和测试Ajax请求非常有用。
摘要由CSDN通过智能技术生成

Ajax-hook

ajax-hook.svgAjax-hook.svg?branch=masterapistatus.svg

typeScript-support-orange.svg

support-%3E%3Des5-orange.svgajaxhook.min.js.svg

6c88c105b679b32c8fe3fbc422ba2d97.png

Introduction

Hook Javascript global XMLHttpRequest object。 And change the default Ajax request and response .

Usage

Installing

Using cdn

Using npm

npm installajax-hook

hook the callbacks and functions you want .

hookAjax({

//hook callbacks

onreadystatechange:function(xhr){

console.log("onreadystatechange called: %O",xhr)

},

onload:function(xhr){

console.log("onload called: %O",xhr)

},

//hook function

open:function(arg,xhr){

console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])

}

})

// NPM

// const ah=require("ajax-hook")

// ah.hookAjax({...})

Now, it worked! we use jQuery ajax to test .

// get current page source code

$.get().done(function(d){

console.log(d.substr(0,30)+"...")

})

The result :

> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true

> onload called: XMLHttpRequest

>

See the demo "demo.html" for more details.

API

hookAjax(ob)

ob; type is Object

return value: original XMLHttpRequest

unHookAjax()

unhook Ajax

Changing the default Ajax behavior

The return value type of all hook-functions is boolean, if true, the ajax will be interrupted ,false or undefined are not . for example:

hookAjax({

open:function(arg,xhr){

if(arg[0]=="GET"){

console.log("Request was aborted! method must be post!")

return true;

}

}

})

Changing the "responseText"

hookAjax({

onload:function(xhr){

console.log("onload called: %O",xhr)

xhr.responseText="hook!"+xhr.responseText;

}

})

Result:

hook!

Notice

All callbacks such as onreadystatechange、onload and son on, the first argument is current XMLHttpRequest instance. All functions, such as open, send and so on, the first parameter is an array of the original parameters, the second parameter is the current origin XMLHttpRequest instance.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值