你是否遇過以下需求:需要為所有 ajax 請求加上統一簽名、想統計某個介面被請求的次數、希望限制 HTTP 請求方法必須為 get 或 post、或想分析別人的網路協議等等?那麼該怎麼做?想想看,如果能攔截所有 ajax 請求,問題就會變得簡單許多!😁 這想法雖大膽,但我欣賞!直接上工具——Ajax-hook 不僅能滿足上述需求,還能帶給你更多可能。
Ajax-hook 原始碼位址:https://github.com/wendux/Ajax-hook
如何使用
1. 引入 ajaxhook.js
<script src="wendu.ajaxhook.js"></script>
2. 攔截需要的 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:https://localhost:63342/Ajax-hook/demo.html,async:true > onload called: XMLHttpRequest > <!DOCTYPE html> <html> <head l...
攔截成功!同時我們也能看到,jQuery 3.1 內部已放棄 onreadystatechange 而改用 onload 了。
API
hookAjax(ob)
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> <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:https://localhost:63342/Ajax-hook/demo.html,async:true send called: null onload called hook<!DOCTYPE html> <html> <he... unhook <!DOCTYPE
注意
1. 攔截函數的返回值為 boolean,若為 true 則會阻斷 ajax 請求,預設為 false,不會阻斷。
2. 所有回調攔截函數的參數為當前的 XMLHttpRequest 實例(如 onreadystatechange、onload);所有 ajax 原始方法的攔截函數,會將原始參數以陣列形式傳給攔截函數,你可以在其中修改它。
以上便是本文介紹的、JS 攔截全域 ajax 請求的實例解析,希望對大家有所幫助。若有任何疑問歡迎留言,我會盡快回覆,也非常感謝大家對網站的支持!