如何使用一. 直接引入脚本引入ajaxhook.js
<script src="wendu.ajaxhook.js"></script>
拦截需要的ajax 回调或函数。
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方法来测一下:
// get current page source code $.get().done(function(d){ console.log(d.substr(0,30)+...) })
结果 :
> open called: method:get,url:http://localhost:63342/ajax-hook/demo.html,async:true > onload called: xmlhttprequest > <!doctype html> <html> 拦截成功了! 我们也可以看到jquery3.1内部已经放弃onreadystatechange而改用onload了。
二. commonjs下的模块构建工具环境中假设在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()
apihookajax(ob)ob,类型是对象,key为想要拦截的回调或函数,value为我们的拦截函数。
返回值: 原始的 xmlhttprequest。如果有写请求不想被拦截,可以new 这个。
unhookajax()卸载拦截;卸载后,拦截将失效。
改变ajax行为拦截所有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>
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>
所有的回调拦截函数的参数为当前的xmlhttprequest 实例,如onreadystatechange、onload;所有ajax原始方法的拦截函数会将原始参数以数组的形式传递给拦截函数,你可以在拦截函数中修改它。
相关推荐:
ajax请求成功后新开窗口window.open()被拦截解决方法
ajax回调打开新窗体防止浏览器拦截有效方法
关于用javascript拦截form的submit方法实现
以上就是js 拦截全局ajax请求的详细内容。
