你是否有過下面的需求:須要給全部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…
本文章容許免費轉載,但請註明原做者及原文連接。