是否有一个JavaScript的方式来听控制台事件? [英] Is there a way in JavaScript to listen console events?

查看:116
本文介绍了是否有一个JavaScript的方式来听控制台事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写在javascript中捕获的异常和浏览器的警告处理。所有的错误和警告应该发送到服务器以后查看。

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: ...");

console.warn("Warning: ...");

所以,他们不是问题,如果他们是从JavaScript code调用,甚至更多,未处理的异常可能与这个和平code的捕获:

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

这样的例外是覆盖pretty但我坚持与浏览器发送到控制台的警告。例如安全或HTML验证警告。下面的例子是从谷歌浏览器的控制台采取

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

https://domainname.com/ 页面跑到离不安全内容
  <一href=\"http://domainname.com/javascripts/$c$cx/MANIFEST.js\">http://domainname.com/javascripts/$c$cx/MANIFEST.js.

The page at https://domainname.com/ ran insecure content from http://domainname.com/javascripts/codex/MANIFEST.js.

如果有喜欢window.onerror但警告某些事件这将是巨大的。有什么想法?

It would be great if there is some event like window.onerror but for warnings. Any thoughts?

推荐答案

您可以只包住控制台方法自己。例如,要记录在一个阵列中的每个呼叫:

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

这篇关于是否有一个JavaScript的方式来听控制台事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆