【发布时间】:2021-10-08 23:40:53
【问题描述】:
所以,我正在开展一个项目,在该项目中,实际生产环境可以访问我无法获得的 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', text)
},
warn: function (text) {
oldCons.warn(text)
addToLogDiv('warn', text)
},
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
关于为什么这没有被我的函数捕获或我能做些什么的任何建议?或者将所有控制台输出输出到 HTML 文档本身的替代方法?
我尝试在文件顶部包含脚本,但所做的只是给了我 2 个无法附加到 null 的错误(对于它正在捕获的 2 个日志条目,但不是对于它所捕获的第三个't)。
我对 Javascript 还很陌生,并试图让现有 AngularJS 代码的基础在新版本的生产环境中工作,该生产环境已从使用 IE 切换到 Chromium 来显示 HTML。
编辑:在Plunker 中放入足够的相关代码。如您所见,控制器中的 console.log('test') 被记录到文档中,但 html 文档正文中未捕获的引用错误却没有。
六个月后编辑:只是想指出问题及其解决方案仍然适用于使用 Typescript 的应用程序(尽管拦截控制台更改的脚本是我的 "scripts": 数组中加载的 JS 文件)生产配置,而不是任何地方都包含在项目中的 Typescript。)
【问题讨论】:
-
当您说 Angular 时,您指的是 AngularJs (Angular 1.x)?
-
不幸的是,是的。项目中的各种文件目前还依赖于 不同 版本的 AngularJS。很痛苦。
-
你能在沙盒站点的工作演示中重现这个吗?
标签: javascript html angular angularjs console.log