Search code examples
javascriptphantomjsmonkeypatching

Monkey-patching console.log in PhantomJS


I am trying to apply monkeypatching to console.log in PhantomJS:

function doTheMonkey( ){
  console._log = console.log; //Typo, was console.log()

  console.log = function log( ){
      console._log.apply( this , arguments );    
      return arguments;
  }
}

PhantomJS will complain about TypeError: Type error for
console._log.apply( this , arguments );

In order to drill down to the easiest example that fails, I can provide this:

function logAndReturn( ){
  console.log.apply( this , arguments );
  return arguments;
}

Similarly, it will fail with TypeError: Type error for
console._log.apply( this , arguments );

This should just work, I have no idea what the root cause is..


Solution

  • As stated in another answer, you should do

    console._log = console.log
    

    Then when you apply the arguments to console._log, you need to do

    console._log.apply(console, Array.prototype.slice.call(arguments));
    

    The arguments value is not an array. With slice you create one.