简体   繁体   中英

Subscribe on console events in a browser

Is there a way to subscribe on some console event from javascript on a page?

Usecase: I want to see an alert window on any js error

something like:

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

NB: I don't ask about catching an exception.

Following instructions on the link in my previous comment , I have created a JSFiddle - Override Console methods .

I still don't know if this is the best way, but this seems to work.

Edit

After discussion, I understood, problem was not just about catching all console messages but to also capture any unhandled errors. In my understanding only way to achieve is to add a Global Exception Handler

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

Following is the Updated JSFiddle . I also have updated the code snippet to show the same.

Code

 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> 

As has been pointed out, there is no global way (that I know of) to subscribe to console events. A partial solution for logging would be to override the console as described by @Rajesh's answer.

For error checking, if you own the code you're trying to check errors for, you can wrap the whole thing in an global try/catch .

try {

  (function() {
    function failingCode() {
      var a;
      return a.foo + 1;

    }

    failingCode();
  })();

}
catch (err) {
  alert('error');
  throw err;
}

For third-party scripts, I can't think of any way of handling this except to load the script via a mechanism like jQuery's getScript . And I'm unclear what happens if that script itself loads additional scripts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM