Have you ever had the following needs: need to add a unified signature to all ajax requests, need to count the number of times a certain interface is requested, need to limit the method of http requests to get or post, need to analyze other people's network protocols, etc. So how? Think about it, if you can intercept all ajax requests, then the problem will become very simple!
Ajax-hook source code address: https://github.com/wendux/Ajax-hook
How to use
1. Introduce ajaxhook.js
2. Intercept the required ajax callbacks or functions.
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, let’s use the get method of jQuery (v3.1) to test:
// get current page source code $.get().done(function(d){ console.log(d.substr(0,30)+"...") })
Result:
> open called: method:GET,url:http://localhost:63342/Ajax-hook/demo.html,async:true > onload called: XMLHttpRequest >Copy after login
The interception was successful! We can also see that jQuery3.1 has abandoned onreadystatechange and used onload instead.
API
##hookAjax(ob)
1.ob, type is object, key is want Interception callback or function, value is our interception function. 2. Return value: original XMLHttpRequest. If you have a write request and don't want to be intercepted, you can use new this.unHookAjax()
1. Load interception; after uninstalling, the interception will be invalid. Change ajax behavior Intercept all ajax requests, detect the request method, if it is "GET", interrupt the request and give a prompthookAjax({ open:function(arg){ if(arg[0]=="GET"){ console.log("Request was aborted! method must be post! ") return true; } } })
hookAjax({ open:function(arg){ arg[1]+="?timestamp="+Date.now(); } })
hookAjax({ onload:function(xhr){ //请求到的数据首部添加"hook!" xhr.responseText="hook!"+xhr.responseText; } })
hook! Copy after login
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 Copy after login
Detailed explanation of interception examples of interceptors for ajax requests
Using Mock.js in Node.js server environment Tutorial on intercepting AJAX requests