覆盖 console.log 等以显示在 HTML 视图中

问题描述

所以,我正在开发一个项目,在该项目中,实际生产环境可以访问我无法获得的 API,除非在生产环境中加载页面(他们使用 angular.$window.external),但是加载生产中的页面意味着我无法访问开发人员工具、控制台等,因为它在应用程序内浏览器实例中运行。因此,我尝试将所有控制台日志/等语句输出到文档中的 div 中,以尝试在我的 API 调用未按预期工作时进行故障排除。

我让它有点工作,但它遗漏了一些东西,我不知道为什么。

我包含的代码consoledebug.js

// Code adapted from https://stackoverflow.com/a/5677825/12869266
// Include consoledebug.js at the end of a file,and create a div with
// the id "logs" in your html file where you want output.

var logDiv = document.getElementById('logs')

var addToLogDiv = function (type,text) {
  var node = document.createElement('p')
  node.className = type
  var content = document.createTextNode(type + ': ' + text)
  node.appendChild(content)
  logDiv.appendChild(node)
}

// define a new console
var console = (function (oldCons) {
  return {
    log: function (text) {
      oldCons.log(text)
      addToLogDiv('log',text)
    },info: function (text) {
      oldCons.info(text)
      addToLogDiv('info',warn: function (text) {
      oldCons.warn(text)
      addToLogDiv('warn',error: function (text) {
      oldCons.error(text)
      addToLogDiv('error',text)
    }
  }
})(window.console)

//Then redefine the old console
window.console = console

我将 <script src="../common/consoledebug.js"></script> 标签放在 HTML 文档的末尾,就在 </body> 标签之前。

当我在一个普通的 chrome 窗口中运行时,我在 HTML 正文中看到这些行:

log: test

error: TypeError: $window.external.someProprietaryAPI is not a function

但 Chrome 的日志显示一个额外的错误 myhtml.html:35 Uncaught ReferenceError: someOtherProprietaryAPI is not defined at myhtml.html:35

关于为什么我的函数没有捕获到这一点或我能做些什么的任何建议?或者将 all 控制台输出输出到 HTML 文档本身的替代方法

我尝试在文件顶部包含脚本,但所做的只是给了我 2 个无法附加到 null 的错误(对于它捕获的 2 个日志条目,但不是对于它不是的第三个日志条目) 't).

我对 Javascript 还很陌生,并试图让现有的 AngularJS 代码在新版本的生产环境中工作,该生产环境已经从使用 IE 切换到 Chromium 以进行 HTML 显示

编辑:在 Plunker 中放入足够多的相关代码。如您所见,控制器中的 console.log('test') 被记录到文档中,但 html 文档正文中未捕获的引用错误没有。

解决方法

一些改进:

  1. 为在完整 dom 加载之前发生的错误创建一个消息队列数组。
  2. 在定义新控制台后使用 window.addEventListener('error',callback) 监听执行错误
  3. 等待 dom 加载以查询 logDiv。在定义之前将消息推送到消息队列中,然后在 dom 加载时检查该队列中的任何内容
let logDiv,messageQueue =[];

window.addEventListener('load',function(){
    // assign the log element
    logDiv = document.getElementById('logs');
    if(messageQueue.length){
        // print your preload errors
        messageQueue.forEach(([type,text])=>addToLogDiv(type,text))
    }
})

var addToLogDiv = function (type,text) {
  if(logDiv){
    var node = document.createElement('p')
    node.className = type
    var content = document.createTextNode(type + ': ' + text)
    node.appendChild(content)
    logDiv.appendChild(node)
  }else{
    // before logDiv defined store any errors
    messageQueue.push([type,text]) 
  } 
}

// define a new console
var console = (function (oldCons) {
  return {
    // same as before
  }
})(window.console)

//Then redefine the old console
window.console = console
// after new console created
window.addEventListener('error',function(e){
  console.log(e.message)
})

Demo in head