【发布时间】:2018-12-19 03:16:28
【问题描述】:
我需要找出警告(非错误)消息何时发送到浏览器的 console.log 。通过研究,我知道我可以使用类似于以下的 JavaScript 代码检测错误消息:
window.onerror = function(errorMsg, url, lineNumber){
// any action you want goes here
// errorMsg is the error message itself.
// url should be the file presenting the error, though i have
// found that it only presents to me the address of the site.
// lineNumber is the line number the error occoured on.
// here is an example of what you could do with it:
alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}
但这只会显示错误消息。它不会显示任何警告消息。
是否有类似的方法来检测 console.log 中的特定警告消息?或者,是否有一些 JS 代码可以让我在 console.log 中搜索特定字符串?
请注意,我可以在浏览器的调试(控制台日志记录)窗口中看到警告消息。但我想“拦截”警告消息并在发现警告时执行一些操作。
已添加
目的是找出特定警告消息何时出现;该消息类似于"Loading failed for the <script> with source "https://www.example.com/js/somescript.js" .
但是如何拦截浏览器输出的警告消息(不是错误;我包含的代码就是这样做的)的问题(不是我的代码)。
已添加
所以,这就是我需要的。假设这段代码
console.warn("Here is a warning!");
您会编写什么代码来查看该消息是否作为警告写入控制台?
【问题讨论】:
-
猴子补丁
console.warn?不过,这似乎是一件很奇怪的事情 -
不;我相信,“可能重复”并没有回答我关于如何“拦截”(或“感知”)console.warn 消息的问题。
-
老兄,你只是覆盖
console.warn它与上面的帖子相同,除了它是console.log -
console.warn 将警告消息写入控制台。我需要在写入警告消息时进行拦截。您可以使用自己的 console.log 函数拦截 console.logs,但我还没有弄清楚如何查找 console.warn 消息。用我有限的 JS 知识/测试创建自己的 console.log 函数是不行的。
标签: javascript