假设我在浏览器中运行我的 Javascript 项目并且我在一个特定的模块中,我可以检查是否已经消息打印到控制台?即从控制台读取消息...
例如,我在我的 js.file 内部函数中想要检查是否已经在控制台中打印了 hello world。
最佳答案
jthanto 的回答给了我一个想法。我不认为这是好的做法,但如果必须,您可以定义自己的控制台类:
var MyConsole = function(oldConsole) {
// store all messages ever logged
this.log = [];
// keep a pointer to oldConsole
this.oldConsole = oldConsole;
}
MyConsole.prototype.log = function(args) {
// push the message into log
this.log.push(Array.prototype.join.call(args));
// call oldConsole.log to actually display the message on the console
if (this.oldConsole)
this.oldConsole.log.apply(this.oldConsole, args);
}
// TODO: implement all other console methods in this fashion (apply for all console API methods)
MyConsole.prototype.<method> = function(args) {
if (this.oldConsole)
this.oldConsole.<method>.apply(this.oldConsole, args);
}
// method to check if something was printed
MyConsole.prototype.wasLogged(message) {
return this.log.indexOf(message)!==-1;
}
// replace console with an instance of MyConsole, pointing to the old console
console = new MyConsole(console);
将它保存在一个文件中并首先加载它(就在你的标签的顶部)
像这样使用它:
if (console.wasLogged("Hello World"))
doStuffz();
希望对您有所帮助。请注意它没有经过测试,但应该给你一些指示:)
关于javascript - 如何查找消息是否已打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31830877/