简体   繁体   English

有没有办法在JavaScript中监听控制台事件?

[英]Is there a way in JavaScript to listen console events?

I'm trying to write handler for uncaught exceptions and browser warnings in Javascript. 我正在尝试在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: 因此,如果从javascript代码调用它们就不会有问题,甚至更多,未处理的异常可以通过这种代码安静来捕获:

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. 例如安全性或html验证警告。 Example below is taken from Google Chrome console 以下示例来自Google Chrome控制台

The page at https://domainname.com/ ran insecure content from http://domainname.com/javascripts/codex/MANIFEST.js . https://domainname.com/上的页面从http://domainname.com/javascripts/codex/MANIFEST.js运行了不安全的内容。

It would be great if there is some event like window.onerror but for warnings. 如果有像window.onerror这样的事件但是警告会很棒。 Any thoughts? 有什么想法吗?

You could just wrap the console methods yourself. 你可以自己包装console方法。 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);
};

More Succint Way: 更多Succint方式:

 // this method will proxy your custom method with the original one function proxy(context, method, message) { return function() { method.apply(context, [message].concat(Array.prototype.slice.apply(arguments))) } } // let's do the actual proxying over originals console.log = proxy(console, console.log, 'Log:') console.error = proxy(console, console.error, 'Error:') console.warn = proxy(console, console.warn, 'Warning:') // let's test console.log('im from console.log', 1, 2, 3); console.error('im from console.error', 1, 2, 3); console.warn('im from console.warn', 1, 2, 3); 

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: 您可以重新定义控制台(以及所有浏览器 )的每个功能的行为,如下所示:

// define a new console
var console = (function(oldCons){
    return {
        log: function(text){
            oldCons.log(text);
            // Your code
        },
        info: function (text) {
            oldCons.info(text);
            // Your code
        },
        warn: function (text) {
            oldCons.warn(text);
            // Your code
        },
        error: function (text) {
            oldCons.error(text);
            // Your code
        }
    };
}(window.console));

//Then redefine the old console
window.console = console;

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 https://github.com/samsonradu/Consolify

在用于执行console.log()的相同功能中,只需将相同的消息发布到您正在记录日志的Web服务上。

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: 记录错误时不会拦截,而是将事件作为错误处理机制的一部分进行触发,并将其记录为事件侦听器之一:

try
{
  //might throw an exception
  foo();
}
catch (e)
{
  $(document).trigger('customerror', e);
}

function customErrorHandler(event, ex)
{
  console.error(ex)
}
function customErrorHandler2(event, ex)
{
  $.post(url, ex);
}

this code uses jQuery and is oversimplified strictly for use as an example. 此代码使用jQuery并严格过度简化以用作示例。

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

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