简体   繁体   English

在页面上显示JavaScript控制台错误

[英]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): 和这样的按钮(带有未定义的onclick处理程序):

<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. 函数'FRANK()'未定义。

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 : 如果要在div中显示页面的任何错误,可以使用全局事件处理程序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. 如果您的目标是拦截控制台中浏览器写入的所有内容,而不仅仅是错误,我不确定它是否可以直接实现,因为浏览器不会使用可访问的console功能。

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.. 我认为@ dystroy的答案就足够了,但是如果你想要正确的错误处理,你应该使用trycatch语句来代替..

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 我们首先创建一个将在单击按钮时调用的函数,并且当您单击该按钮时, try块中的代码将被执行,如果它有任何错误,我们将使用catch语句抛出错误,其中使用throw_error.message打印错误消息,最后,我们使用setTimeout清除2000的错误消息,即2秒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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