Can I extend the console object (for rerouting the logging) in javascript?

前端 未结 6 1864
误落风尘
误落风尘 2020-11-30 08:33

Is it possible to extend the console object?

I tried something like:

Console.prototype.log = function(msg){
    Console.prototype.log.call(msg);
             


        
6条回答
  •  余生分开走
    2020-11-30 08:59

    For ECMAScript 2015 and later

    You can use the newer Proxy feature from the ECMAScript 2015 standard to "hijack" the global console.log.

    Source-Code

    'use strict';
    
    class Mocker {
      static mockConsoleLog() {
        Mocker.oldGlobalConsole = window.console;
    
        window.console = new Proxy(window.console, {
          get(target, property) {
            if (property === 'log') {
              return function(...parameters) {
                Mocker.consoleLogReturnValue = parameters.join(' ');
              }
            }
    
            return target[property];
          }
        });
      }
    
      static unmockConsoleLog() {
        window.console = Mocker.oldGlobalConsole;
      }
    }
    
    Mocker.mockConsoleLog();
    
    console.log('hello'); // nothing happens here
    
    Mocker.unmockConsoleLog();
    
    if (Mocker.consoleLogReturnValue === 'hello') {
      console.log('Hello world!'); // Hello world!
      alert(Mocker.consoleLogReturnValue);
      // anything you want to do with the console log return value here...
    }
    

    Online Demo

    Repl.it.

    Node.js users...

    ... I do not forget you. You can take this source-code and replace window.console by gloabl.console to properly reference the console object (and of course, get rid of the alert call). In fact, I wrote this code initially and tested it on Node.js.

提交回复
热议问题