简体   繁体   中英

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>

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

I think @dystroy's answer is sufficient here, but if you want proper error handling, you should be using try and catch statements instead..

Demo

function throw_msg() {
    try {
        var a = '';
        alert(b);
    }
    catch(throw_error) {
        document.getElementById('error-box').innerHTML=throw_error.message;
        setTimeout(
            function() {
                document.getElementById('error-box').innerHTML='';
            }, 2000);
    }
}

Explanation for the above code :

We are first creating a function which will be called on click of the button, and than when you click the button, the code in the try block gets executed, if it has any error, we then throw the error using the catch statement where the error message is printed using throw_error.message and at the end, we use setTimeout to clear out the error message in 2000 ie 2 seconds

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