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

发布于 2024-12-13 16:31:57 字数 786 浏览 1 评论 0原文

我正在尝试用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

撩心不撩汉 2024-12-20 16:31:57

您可以自己包装 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);
};

You could just wrap the console methods yourself. 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);
};
始于初秋 2024-12-20 16:31:57

更简洁的方式:

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

More Succint Way:

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

别低头,皇冠会掉 2024-12-20 16:31:57

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

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

// 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 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;
眼眸 2024-12-20 16:31:57

我需要在移动设备上调试控制台输出,因此我构建了这个嵌入式库来捕获控制台输出和类别并将其转储到页面。查看源码,很简单。

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

笙痞 2024-12-20 16:31:57

在您用于执行 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.

关于从前 2024-12-20 16:31:57

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

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,并且严格用作示例而过于简单。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文