簡介
web調試有幾個非常頻繁的剛需:看log、看error、看AJAX發包與回包。其他的如timeline和cookie以及localstorage就不是那么頻繁,但是AlloyLever都支持。如你所見:
特征
- 點擊alloylever按鈕之間切換顯示或隱藏工具面板
- Console會輸出所有用戶打印的日志如console.[log/error/info/debug/debug]
- Console會輸出所有的錯誤信息(腳本錯誤和網絡請求錯誤)
- XHR面板會輸出所有(XMLHttpRequest)AJAX請求和服務器端返回的數據
- Resouces面板會輸出所有的Cookie信息和LocalStorage
- TimeLime面板會輸出頁面相關的生命周期里的時間段耗時情況
演示
http://alloyteam.github.io/AlloyLever/
Install
可以通過npm安裝:
npm install alloylever
使用
你的頁面只需要引用一個js即可!
<script src="alloylever.js"></script>
但是需要注意的是,該js必須引用在其他腳本之前。至於為什么,看下面的原理。
Console截獲
window.console = {
wc: window.console
};
var self = this;
['log', 'error', 'warn', 'debug', 'info'].forEach(function (item) {
console[item] = function (msg) {
this.wc[item](msg);
self.log(msg, item);
}
});
重寫了console方法,並且保存下window下真正的方法進行執行,並且注入自己的事件。
AJAX截獲
var XHR = window.XMLHttpRequest;
window.XMLHttpRequest=function(){
var xhr = new XHR();
checkSuccess(xhr);
return xhr;
};
window.XMLHttpRequest.realXHR = XHR;
var self=this;
function checkSuccess(xhr) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
self.option.xhrs.push({url:xhr.responseURL, json:JSON.stringify(JSON.parse( xhr.responseText), null, "\t")})
}else if(xhr.status>=400) {
console.error(xhr.responseURL +' '+xhr.status+' ('+xhr.statusText+')')
}
else{
window.setTimeout(function () {
checkSuccess(xhr);
}, 0);
}
}
如上面所示,重寫了XMLHttpRequest對象。用戶new的對象全部為重寫后的,返回的是真正的。這樣就可以拿到所有用戶創建的XMLHttpRequest對象的實例進行監聽。
Error截獲
其中error包含兩部分,第一部分是js報的錯誤,通過下面的方式截獲:
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.error('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
+ ' Column: ' + column + ' StackTrace: ' + errorObj);
}
這里執行的時候console已經被重寫了。所以自己的console面板也能看到錯誤。
第二部分是資源加載失敗報的錯,通過遍歷HTML dom節點拿到所有的 js/css/img,然后再次發送請求。js和css通過XMLHttpRequest發請求,監聽狀態。,img通過new Image(),監聽onerror。具體代碼參見: https://github.com/AlloyTeam/AlloyLever/blob/master/src/component/alloy_lever/index.js
其他
Timeline通過timing.js獲得所有信息,timing.js基於window.performance封裝的類庫。Cookie和localStorage通過js遍歷得到。
相關
Github: https://github.com/AlloyTeam/AlloyLever
Issues: https://github.com/AlloyTeam/AlloyLever/issues
歡迎試用反饋。