简体   繁体   English

如何在 JavaScript 中从 Chrome 的控制台读取

[英]How to read from Chrome's console in JavaScript

I would like to put a button in my app, if you press it it will get the contents of everything that was written to the console and email it to me (for reporting bugs).我想在我的应用程序中放置一个按钮,如果您按下它,它将获取写入控制台的所有内容并将其通过电子邮件发送给我(用于报告错误)。 I know I can keep a variable around and every time I do a console.log also append the message to that variable but I am trying to keep the memory consumption of the app low so it would be much more efficient just to grab it from the console.我知道我可以保留一个变量,每次执行 console.log 时也会将消息附加到该变量,但我试图保持应用程序的内存消耗较低,因此从安慰。

Is there a way to retrieve the console messages from javascript?有没有办法从 javascript 中检索控制台消息?

You can't.你不能。 What's in the console can't be read from JavaScript.无法从 JavaScript 读取控制台中的内容。

What you can do is hook the console.log function so that you store when it logs :您可以做的是挂钩console.log功能,以便您在记录时存储:

console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
    console.logs.push(Array.from(arguments));
    console.stdlog.apply(console, arguments);
}

console.logs contains all what was logged. console.logs包含所有记录的内容。 You can clean it at any time by doing console.logs.length = 0;您可以随时通过执行console.logs.length = 0;来清理它。 . .

You can still do a standard, non storing, log by calling console.stdlog .你仍然可以通过调用console.stdlog来做一个标准的、非存储的日志。

get all console data获取所有控制台数据

how to read browser console error in js?如何在js中读取浏览器控制台错误?

How to read from Chrome's console in JavaScript 如何在 JavaScript 中从 Chrome 的控制台读取

https://www.quora.com/How-do-I-read-console-window-errors-from-Chrome-using-JavaScript https://www.quora.com/How-do-I-read-console-window-errors-from-Chrome-using-JavaScript

logs日志

console.defaultLog = console.log.bind(console);
console.logs = [];
console.log = function(){
    // default &  console.log()
    console.defaultLog.apply(console, arguments);
    // new & array data
    console.logs.push(Array.from(arguments));
}

error错误

console.defaultError = console.error.bind(console);
console.errors = [];
console.error = function(){
    // default &  console.error()
    console.defaultError.apply(console, arguments);
    // new & array data
    console.errors.push(Array.from(arguments));
}

warn警告

console.defaultWarn = console.warn.bind(console);
console.warns = [];
console.warn = function(){
    // default &  console.warn()
    console.defaultWarn.apply(console, arguments);
    // new & array data
    console.warns.push(Array.from(arguments));
}

debug调试

console.defaultDebug = console.debug.bind(console);
console.debugs = [];
console.debug = function(){
    // default &  console.debug()
    console.defaultDebug.apply(console, arguments);
    // new & array data
    console.debugs.push(Array.from(arguments));
}

I have used this code in the past to capture all console activity and store it with types and timestamps in console.everything for sending back to the server for diagnosing form data entry issues.我过去曾使用此代码来捕获所有控制台活动并将其与类型时间戳一起存储在console.everything中。所有内容都用于发送回服务器以诊断表单数据输入问题。 I run this code as early as possible in the <head> element.我尽可能早地在<head>元素中运行此代码。

if (console.everything === undefined)
{
    console.everything = [];

    console.defaultLog = console.log.bind(console);
    console.log = function(){
        console.everything.push({"type":"log", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
        console.defaultLog.apply(console, arguments);
    }
    console.defaultError = console.error.bind(console);
    console.error = function(){
        console.everything.push({"type":"error", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
        console.defaultError.apply(console, arguments);
    }
    console.defaultWarn = console.warn.bind(console);
    console.warn = function(){
        console.everything.push({"type":"warn", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
        console.defaultWarn.apply(console, arguments);
    }
    console.defaultDebug = console.debug.bind(console);
    console.debug = function(){
        console.everything.push({"type":"debug", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
        console.defaultDebug.apply(console, arguments);
    }
}

QA Collective 's solution is very nice but has a lot of repeated code and doesn't capture errors that are not printed via the console.log , console.error , etc. QA Collective的解决方案非常好,但有很多重复的代码,并且不会捕获未通过console.logconsole.error等打印的错误。

Here's the DRY and extended version of his solution that captures more error messages that show up in the console:这是他的解决方案的 DRY 和扩展版本,它捕获了控制台中显示的更多错误消息:

if (console.everything === undefined) {
  console.everything = [];
  function TS(){
    return (new Date).toLocaleString("sv", { timeZone: 'UTC' }) + "Z"
  }
  window.onerror = function (error, url, line) {
    console.everything.push({
      type: "exception",
      timeStamp: TS(),
      value: { error, url, line }
    })
    return false;
  }
  window.onunhandledrejection = function (e) {
    console.everything.push({
      type: "promiseRejection",
      timeStamp: TS(),
      value: e.reason
    })
  } 

  function hookLogType(logType) {
    const original= console[logType].bind(console)
    return function(){
      console.everything.push({ 
        type: logType, 
        timeStamp: TS(), 
        value: Array.from(arguments) 
      })
      original.apply(console, arguments)
    }
  }

  ['log', 'error', 'warn', 'debug'].forEach(logType=>{
    console[logType] = hookLogType(logType)
  })
}   

I also changed the timestamp format to use the ISO format in UTC timezone, to be able to compare time stamps in different time zones more easily.我还更改了时间戳格式以使用 UTC 时区的 ISO 格式,以便能够更轻松地比较不同时区的时间戳。

If you're working on vue.js , you can actually do this:如果您正在使用vue.js ,您实际上可以这样做:

data () {
    return {
        data: []
    }
},
created () {
    let current_log = console.log;

    console.log = msg => {
        if (msg !== undefined) this.data.push(msg);
        current_log.apply(null, arguments);
    }
}

All logs from console will be captured and stored in data来自控制台的所有日志都将被捕获并存储在data

If you just want to catch windows errors (Browser's developer tool), you just need to use the window.onerror listener.如果你只是想捕捉 windows 错误(浏览器的开发者工具),你只需要使用 window.onerror 监听器。 and the most important thing is to keep returning it false because If you return true in your callback, then the propagation of the error will stop and won't be log in the console anymore .最重要的是保持返回 false 因为如果您在回调中返回 true,则错误的传播将停止并且不会再登录控制台。

window.onerror = function myErrorHandler(err, url, line) {  
    //Do some  stuff 
    console.log(err) // Uncaught SyntaxError: Invalid or unexpected token at Line no:- 1
    return false;   // so you still log errors into console 
}

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

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