简体   繁体   中英

display messages from the javascript console

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:

  1. We declare a variable console with the actual console. If the console is undefined we just stop right away and leave the function.

  2. We declare var methods = ['log', 'warn', 'error'] for the different console message types

  3. We loop through the methods and call the intercept function and send the console type (string: 'log', 'warn', etc).
  4. 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.

  5. We retrieve the message and put it in the message variable.

  6. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM