在浏览器中订阅控制台事件

Subscribe on console events in a browser

本文关键字:控制台 事件 浏览器      更新时间:2023-09-26

有没有办法从页面上的javascript订阅一些控制台事件?

用例:我想在任何js错误上看到一个警告窗口

类似于:

console.on('error', => alert('There is an error! Look in console window'))
console.on('log', => alert('Something log to console'))

注意:我不要求捕捉异常。

按照我上一条评论中链接上的说明,我创建了一个JSFiddle-Override控制台方法。

我仍然不知道这是否是最好的方法,但这似乎奏效了。

编辑

经过讨论,我明白了,问题不仅在于捕获所有控制台消息,还在于捕获任何未处理的错误。据我所知,实现这一目标的唯一方法是添加一个全局异常处理程序

window.onerror = function(error){
    // do your stuff
}

以下是更新后的JSFiddle。我还更新了代码片段以显示相同的内容。

代码

var error = window.console.error,
	log = console.log,
    info = console.info,
    warn = console.warn;
var lastLog = "", 
    lastError="",
    lastInfo="",
    lastWarn="";
function overrideConsole(){
    console.error = function () {
        lastError = arguments;
        //alert(lastError);
        print(lastError, "error")
        error.apply(console, arguments);
    };
    
    console.log = function () {
        lastLog = arguments;
        print(lastLog, "log");
        log.apply(console, arguments);
    };
    
    console.info = function () {
        lastInfo = arguments;
        print(lastInfo, "info");
        info.apply(console, arguments);
    };
    
    console.warn = function () {
        lastWarn = arguments;
        print(lastWarn, "warn");
        warn.apply(console, arguments);
    };
}
function registerEvents(){
	$("#btnError").on("click", function(){
    	console.error("new error");
    });
    
    $("#btnLog").on("click", function(){
    	console.log("new log");
    });
    
    $("#btnInfo").on("click", function(){
    	console.info("new info");
    });
    
    $("#btnWarn").on("click", function(){
    	console.warn("new warn");
    });
    
    $("#btnException").on("click", function(){
    	throw new Error();
    });
}
function registerGlobalHandler(){
	window.onerror = function(error) {
    	console.error(error);
	};
}
function print(str, type){
    var msgClass= "";
    
    switch(type){
        case "log": msgClass=" log"; break;
        case "error": msgClass=" error"; break;
        case "info": msgClass=" info"; break;
        case "warn": msgClass=" warn"; break;
    }
	var div = "<div class='cell'>"+
        	"<label class='"+msgClass+"'>"+ str[0]+"</label>" +
        "</div>"
    $(".content").html( div + $(".content").html());
}
(function init(){
	registerEvents();
    registerGlobalHandler();
    overrideConsole();
  
    // Undefined function call
    test();
})();
.cell{
    width:90%;
    position:relative;
    padding:5px;
    background: #eee;
}
.info{
    color:blue;
}
.error{
    color:red;
}
.warn{
    color:green;
}
.log{
    color:black;
}
.content{
    width:90%;
    height:300%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btnError">Error</button>
<button id="btnLog">Log</button>
<button id="btnInfo">Info</button>
<button id="btnWarn">Warn</button>
<button id="btnException">Exception</button>
<div class="content"></div>

正如已经指出的,没有全局方式(据我所知)订阅控制台事件。日志记录的部分解决方案是覆盖控制台,如@Rajesh的回答所述。

对于错误检查,如果您拥有要检查错误的代码,则可以将整个代码封装在全局try/catch中。

try {
  (function() {
    function failingCode() {
      var a;
      return a.foo + 1;
    }
    failingCode();
  })();
}
catch (err) {
  alert('error');
  throw err;
}

对于第三方脚本,除了通过jQuery的getScript之类的机制加载脚本之外,我想不出任何方法来处理这个问题。我不清楚如果脚本本身加载了额外的脚本会发生什么。