移動web開發除錯工具AlloyLever介紹

發表於2016-05-13

簡介

web除錯有幾個非常頻繁的剛需:看log、看error、看AJAX發包與回包。其他的如timeline和cookie以及localstorage就不是那麼頻繁,但是AlloyLever都支援。如你所見:

pv

特徵

  • 點選alloylever按鈕之間切換顯示或隱藏工具皮膚
  • Console會輸出所有使用者列印的日誌如console.[log/error/info/debug/debug]
  • Console會輸出所有的錯誤資訊(指令碼錯誤和網路請求錯誤)
  • XHR皮膚會輸出所有(XMLHttpRequest)AJAX請求和伺服器端返回的資料
  • Resouces皮膚會輸出所有的Cookie資訊和LocalStorage
  • TimeLime皮膚會輸出頁面相關的生命週期裡的時間段耗時情況

演示

demo

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

歡迎試用反饋。

相關文章