Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show JavaScript console errors on the page

Let's say I have the following code:

<script>

    function billy() {
        alert('muahahahaha!');
    }

    function suzzy() {
        return;
    }

</script>

and a button like this (with an undefined onclick handler):

<input type='button' value='click me' onClick='FRANK()' />

When I click the button, the following appears in the developer console:

Function 'FRANK()' is not defined.

How could I store that message in a variable and display it on the page?

document.getElementById('prompt').innerHTML = log;

So it would appear as:

<div id='prompt'>
    Function 'FRANK()' has not been defined.
</div>
like image 567
XRipperxMetalX Avatar asked May 27 '14 05:05

XRipperxMetalX


1 Answers

If you want to display any error of the page in your div, you may use the global event handler onerror :

window.onerror = function(e){
  document.getElementById('prompt').innerHTML = e.toString();
}

Demonstration


If your goal is to intercept all what is written by the browser in the console, not only the errors, I'm not sure it's directly possible as the browser doesn't use the accessible console functions for everything.

But you can do a lot by hooking all global event handlers :

Demonstration

like image 140
Denys Séguret Avatar answered Sep 18 '22 10:09

Denys Séguret