显示来自javascript控制台的消息 [英] display messages from the javascript console
问题描述
我如何使用javascript来循环遍历javascript控制台中的消息,并将它们显示给用户,例如将它们逐行添加到容器元素,如 div
。
我知道如何使用 console.log
向控制台添加消息,但我的问题是,
要做到这一点,想法是拦截发送到控制台的任何东西。这里是一个跨浏览器解决方案。
函数takeOverConsole(){
var console = window.console
if(!console)return
function intercept(method){
var original = console [method]
console [method] = function(){
var message = Array.prototype.slice.apply .join('')
//做偷偷的东西
if(original.call){
//对于普通浏览器这样做
original.call(console,message)
} else {
//为IE
执行此操作(消息)
}
}
}
var methods = ['log' ,'warn','error']
for(var i = 0; i intercept(methods [i])
}
/ code>
这里我调用函数, 嘿。它会干扰它,我会提醒截获的消息。 http://jsfiddle.net/Grimbode/zetcpm1a/
要解释此函数的工作原理:
-
我们声明一个变量
console
与实际控制台。如果console
是undefined
,我们立即停止并离开函数。 -
我们对不同的控制台消息类型声明
var methods = ['log','warn','error']
- 我们循环遍历这些方法并调用
拦截
函数并发送控制台类型
(string:'log','warn',etc)。 -
拦截功能只是将侦听器应用于该类型的控制台消息。
-
我们检索消息并将其放入消息变量中。
/ li>
-
因为我们拦截了消息,所以它不会显示在控制台中,所以我们继续使用original.call()或original()将它添加到控制台。
how would I use javascript to loop through the messages in the javascript console and display them to a user, for example adding them line by line to a container element like a div
.
I understand how to add messages to the console with console.log
but my question is, is there any way to then retrieve messages that have been added.
To do this the idea is to intercept anything being sent to the console. Here is a cross browser solution.
function takeOverConsole(){
var console = window.console
if (!console) return
function intercept(method){
var original = console[method]
console[method] = function(){
var message = Array.prototype.slice.apply(arguments).join(' ')
// do sneaky stuff
if (original.call){
// Do this for normal browsers
original.call(console, message)
}else{
// Do this for IE
original(message)
}
}
}
var methods = ['log', 'warn', 'error']
for (var i = 0; i < methods.length; i++)
intercept(methods[i])
}
Found this from taking-over-console-log/
Here I call the the function, and do a simple log "hey". It will interecept it and I will alert the intercepted message. http://jsfiddle.net/Grimbode/zetcpm1a/
To explain how this function works:
We declare a variable
console
with the actual console. If theconsole
isundefined
we just stop right away and leave the function.We declare
var methods = ['log', 'warn', 'error']
for the different console message types- We loop through the methods and call the
intercept
function and send theconsole type
(string: 'log', 'warn', etc). Intercept function simply applies a listener~ to that type of console message. In our case we are applying a listener to log, warn and error.
We retrieve the message and put it in the message variable.
Since we intercepted the message, it won't be shown in the console, so we go ahead and original.call() or original() to add it to the console.
这篇关于显示来自javascript控制台的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!