在 html 元素中显示控制台日志结果

问题描述

  • 可以捕获浏览器控制台日志并将其显示在 html 元素中 console.log() 我认为这没什么,它只是添加了与 console.log = (masg) => elem.innerHTML = msg 同名的新函数,但我需要在通过它并显示错误或对象、数组等后获取控制台的值。 . 结果
  • 我的问题是如何获取控制台的所有日志并将其显示在 html 元素中,而不仅仅是错误,还有测试结果,任何人都可以帮助我

解决方法

您可以使用此代码

console.log = function(...logs) 
{
    var text = logs.map(e=> JSON.stringify(e)).join(' ');
    elem.innerHTML = text;
}

注意圆形结构。它会带来错误。

扩展变体

var consoleLog = console.log;
console.log = console.error = console.warn = function(...logs) {

    var text = logs.map(e=> {
                   if (e instanceof Error) return `Error: ${e.message}`;
                   else if (Array.isArray(e)) return `<ul>${e.map(l => `<li>${l}</li>`).join('')}</ul>`;
                   // other stuff
                   else {
                       try {
                           return JSON.stringify(e);
                       } catch(e) {
                           consoleLog(...logs);
                           return `${e.message}<br/>See the console for details`;
                       }
                   }
               }).join(' ');

    elem.innerHTML = text;
}