繁体   English   中英

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

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

我正在尝试在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这样的事件但是警告会很棒。 有什么想法吗?

你可以自己包装console方法。 例如,要在数组中记录每个调用:

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);
};

更多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); 

我知道这是一个旧帖子,但它无论如何都可能有用,因为其他解决方案与旧浏览器不兼容。

您可以重新定义控制台(以及所有浏览器 )的每个功能的行为,如下所示:

// 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;

我需要在移动设备上调试控制台输出,因此我构建了这个插件库以捕获控制台输出和类别并将其转储到页面。 检查源代码,这非常简单。

https://github.com/samsonradu/Consolify

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

你正在倒退这个。 记录错误时不会拦截,而是将事件作为错误处理机制的一部分进行触发,并将其记录为事件侦听器之一:

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);
}

此代码使用jQuery并严格过度简化以用作示例。

暂无
暂无

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

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