UNPKG

console-listener

Version:

A lightweight utility to intercept and handle console method calls.

64 lines (59 loc) 2.09 kB
define((function () { 'use strict'; class ConsoleListener { // 是否为内部调用 #isInternalCall; constructor() { this.consoleMethods = ["assert", "clear", "count", "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "table", "time", "timeEnd", "timeStamp", "trace", "warn"]; this.allHandlers = []; this.methodObj = {}; this.#isInternalCall = false; this.initializeMethods(); } initializeMethods() { for (const method of this.consoleMethods) { this.methodObj[method] = { handlers: [] }; this.overrideMethod(method); } } overrideMethod(methodName) { if (!console[methodName]) return; const originalMethod = console[methodName]; console[methodName] = (...args) => { if (this.#isInternalCall) { // 如果是内部调用,直接执行原始方法,防止递归 originalMethod(...args); return; } // 否则,正常触发监听器 this.#isInternalCall = true; for (const handler of this.methodObj[methodName].handlers) { handler(...args); } for (const handler of this.allHandlers) { handler(methodName, ...args); } this.#isInternalCall = false; originalMethod(...args); }; } on(methodName, callback) { if (typeof methodName === "function") { this.allHandlers.push(methodName); } else if (typeof methodName === "string" && methodName in this.methodObj) { this.methodObj[methodName].handlers.push(callback); } else if (typeof methodName === "object") { for (const key in methodName) { if (key === "all") { this.allHandlers.push(methodName[key]); } else if (key in this.methodObj) { this.methodObj[key].handlers.push(methodName[key]); } } } } } return ConsoleListener; })); //# sourceMappingURL=console-listener.amd.js.map