Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in JavaScript to listen console events?

I'm trying to write handler for uncaught exceptions and browser warnings in Javascript. All errors and warnings should be sent to server for later review.

Handled exceptions can be caught and easily logged with

console.error("Error: ..."); 

or

console.warn("Warning: ..."); 

So they are not problem if they are called from javascript code, even more, unhandled exceptions could be caught with this peace of code:

window.onerror = function(){     // add to errors Stack trace etc.    }); } 

so exceptions are pretty covered but I've stuck with warnings which browser sends to console. For instance security or html validation warnings. Example below is taken from Google Chrome console

The page at https://domainname.com/ ran insecure content from http://domainname.com/javascripts/codex/MANIFEST.js.

It would be great if there is some event like window.onerror but for warnings. Any thoughts?

like image 570
Milan Jaric Avatar asked Nov 03 '11 18:11

Milan Jaric


People also ask

Can JavaScript read the console?

You can't. What's in the console can't be read from JavaScript. console. logs contains all what was logged.

How does event listener work in JavaScript?

Event listeners are called only when the event happens in the context of the object they are registered on. That example attaches a handler to the button node. Clicks on the button cause that handler to run, but clicks on the rest of the document do not. Giving a node an onclick attribute has a similar effect.

How do I run a JavaScript console log?

The JavaScript console log function is mainly used for code debugging as it makes the JavaScript print the output to the console. To open the browser console, right-click on the page and select Inspect, and then click Console.


1 Answers

You could just wrap the console methods yourself. For example, to record each call in an array:

var logOfConsole = [];  var _log = console.log,     _warn = console.warn,     _error = console.error;  console.log = function() {     logOfConsole.push({method: 'log', arguments: arguments});     return _log.apply(console, arguments); };  console.warn = function() {     logOfConsole.push({method: 'warn', arguments: arguments});     return _warn.apply(console, arguments); };  console.error = function() {     logOfConsole.push({method: 'error', arguments: arguments});     return _error.apply(console, arguments); }; 
like image 164
Jeremy Avatar answered Sep 22 '22 23:09

Jeremy