JavaScript 有没有办法监听控制台事件?
我正在尝试用 JavaScript 编写未捕获异常和浏览器警告的处理程序。所有错误和警告均应发送到服务器以供稍后查看。
可以捕获并轻松记录已处理的异常
console.error("Error: ...");
,
console.warn("Warning: ...");
因此如果从 javascript 代码调用它们,它们就不是问题,更重要的是,可以使用这种和平的代码捕获未处理的异常:
window.onerror = function(){
// add to errors Stack trace etc.
});
}
因此异常已被很好地覆盖,但我坚持使用警告浏览器发送到控制台。例如安全或 html 验证警告。下面的示例取自 Google Chrome 控制台
https://domainname.com/ 的页面运行了来自以下位置的不安全内容 http://domainname.com/javascripts/codex/MANIFEST.js。
如果有像 window.onerror 这样的事件但用于警告,那就太好了。有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以自己包装
console
方法。例如,将每个调用记录在数组中:You could just wrap the
console
methods yourself. For example, to record each call in an array:更简洁的方式:
More Succint Way:
我知道这是一篇旧帖子,但无论如何它都是有用的,因为其他解决方案与旧版浏览器不兼容。
您可以重新定义控制台(以及所有浏览器)的每个功能的行为,如下所示:
I know it's an old post but it can be useful anyway as others solution are not compatible with older browsers.
You can redefine the behavior of each function of the console (and for all browsers) like this:
我需要在移动设备上调试控制台输出,因此我构建了这个嵌入式库来捕获控制台输出和类别并将其转储到页面。查看源码,很简单。
https://github.com/samsonradu/Consolify
I needed to debug console output on mobile devices so I built this drop-in library to capture console output and category and dump it to the page. Check the source code, it's quite straightforward.
https://github.com/samsonradu/Consolify
在您用于执行 console.log() 的同一函数中,只需将相同的消息发布到您正在记录日志的 Web 服务即可。
In the same function that you are using to do console.log(), simply post the same message to a web service that you are recording the logs on.
你正在倒退。不是在记录错误时进行拦截,而是触发一个事件作为错误处理机制的一部分,并将其记录为事件侦听器之一:
此代码使用 jQuery,并且严格用作示例而过于简单。
You're going about this backwards. Instead of intercepting when an error is logged, trigger an event as part of the error handling mechanism and log it as one of the event listeners:
this code uses jQuery and is oversimplified strictly for use as an example.