你是否有过下面的需求:须要给全部ajax请求添加统一签名、须要统计某个接口被请求的次数、须要限制http请求的方法必须为get或post、须要分析别人网络协议等等,那么如何作?想一想,若是可以拦截全部ajax请求,那么问题就会变的很简单!😄,少年,想法有点大胆,不过,我欣赏!直接上轮子,Ajax-hook不只能够知足你想要的,同时能够给你更多。javascript
本博客原始地址:www.jianshu.com/p/9b634f1c9…
Ajax-hook源码地址 : github.com/wendux/Ajax… 欢迎starhtml
注:本文为做者以前在简书博客发布的文章,掘金原创权限刚开,复制过来,若是您以前看过,跳过吧!java
###一. 直接引入脚本webpack
引入ajaxhook.jsgit
<script src="wendu.ajaxhook.js"></script>复制代码
拦截须要的ajax 回调或函数。github
hookAjax({
//拦截回调
onreadystatechange:function(xhr){
console.log("onreadystatechange called: %O",xhr)
},
onload:function(xhr){
console.log("onload called: %O",xhr)
},
//拦截函数
open:function(arg){
console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])
}
})复制代码
ok, 咱们使用jQuery(v3.1) 的get方法来测一下:web
// get current page source code
$.get().done(function(d){
console.log(d.substr(0,30)+"...")
})复制代码
结果 :ajax
> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true
> onload called: XMLHttpRequest
> <!DOCTYPE html>
<html>
<head l...复制代码
拦截成功了! 咱们也能够看到jQuery3.1内部已经放弃onreadystatechange而改用onload了。npm
###二. CommonJs下的模块构建工具环境中api
假设在webpack下,第一步, 安装ajax-hook npm插件
npm install ajax-hook --save-dev复制代码
第二步,引入模块并调用api:
const ah=require("ajax-hook")
ah.hookAjax({
onreadystatechange:function(xhr){ ... },
onload:function(xhr){ ... },
...
})
...
ah.unHookAjax()复制代码
拦截全部ajax请求,检测请求method,若是是“GET”,则中断请求并给出提示
hookAjax({
open:function(arg){
if(arg[0]=="GET"){
console.log("Request was aborted! method must be post! ")
return true;
}
}
})复制代码
拦截全部ajax请求,请求统一添加时间戳
hookAjax({
open:function(arg){
arg[1]+="?timestamp="+Date.now();
}
})复制代码
修改请求返回的数据“responseText”
hookAjax({
onload:function(xhr){
//请求到的数据首部添加"hook!"
xhr.responseText="hook!"+xhr.responseText;
}
})复制代码
结果:
hook!<!DOCTYPE html>
<html>
<h...复制代码
有了这些示例,相信开篇提到的需求都很容易实现。最后测一下unHook
hookAjax({
onreadystatechange:function(xhr){
console.log("onreadystatechange called: %O",xhr)
//return true
},
onload:function(xhr){
console.log("onload called")
xhr.responseText="hook"+xhr.responseText;
//return true;
},
open:function(arg){
console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2])
arg[1]+="?hook_tag=1";
},
send:function(arg){
console.log("send called: %O",arg[0])
}
})
$.get().done(function(d){
console.log(d.substr(0,30)+"...")
//use original XMLHttpRequest
console.log("unhook")
unHookAjax()
$.get().done(function(d){
console.log(d.substr(0,10))
})
})复制代码
输出:
open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true
send called: null
onload called
hook<!DOCTYPE html>
<html>
<he...
unhook
<!DOCTYPE复制代码
相关连接:
Ajax-hook原理解析:www.jianshu.com/p/7337ac624…
本文章容许免费转载,但请注明原做者及原文连接。