4

で発生するすべてのイベント/エラー/ログをキャプチャしconsoleて、画面上の要素に表示することはできますか? これは JavaScript で実行できますか?

4

3 に答える 3

4

のイベントconsoleをタップするだけでなく、いつでもメソッドをオーバーライドできます。イベントのリッスンを含むオーバーライドの例を次に示します。windowerrorerror

(function () {
    "use strict";

    var methods, generateNewMethod, i, j, cur, old, addEvent;

    if ("console" in window) {
        methods = [
            "log", "assert", "clear", "count",
            "debug", "dir", "dirxml", "error",
            "exception", "group", "groupCollapsed",
            "groupEnd", "info", "profile", "profileEnd",
            "table", "time", "timeEnd", "timeStamp",
            "trace", "warn"
        ];

        generateNewMethod = function (oldCallback, methodName) {
            return function () {
                var args;
                alert("called console." + methodName + ", with " + arguments.length + " argument(s)");
                args = Array.prototype.slice.call(arguments, 0);
                Function.prototype.apply.call(oldCallback, console, arguments);
            };
        };

        for (i = 0, j = methods.length; i < j; i++) {
            cur = methods[i];
            if (cur in console) {
                old = console[cur];
                console[cur] = generateNewMethod(old, cur);
            }
        }
    }

    window.onerror = function (msg, url, line) {
        alert("Window error: " + msg + ", " + url + ", line " + line);
    };
}());

console.log("ahh", "fdsa");
console.warn("f");

(function () {
    throw new Error("asdf");
}());

デモ: http://jsfiddle.net/HfPJ8/

于 2013-06-18T21:45:53.280 に答える
0

独自のロギング フレームワークを作成するか、 log4javascriptなどの利用可能なフレームワークを使用できますが、コンソールからの出力をリダイレクトできるものはないと思います。エラーまたはグローバル エラー リスナーtry..catchをキャッチするために使用する必要があります。 (これはブラウザー全体であまり信頼性がありません)、フレームワークのメソッドを介してそれらをログに記録します。

于 2013-06-18T21:41:15.223 に答える