微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。