Home > Back-end >  Intercepting a console.log created by a node_module to display in a toast
Intercepting a console.log created by a node_module to display in a toast

Time:04-17

I am trying to use a console.log() created from within a node_module to display a toast on screen for the user.

I have my toasts working. I'm just not sure how to capture the log message since it is not being created from my personal code. Is this possible?

CodePudding user response:

WARNING: This is extremely bad practice. It is not recommended to change the behavior of a native function especially not console.log.

That being said you can technically intercept logs by redefining the log function and then using console.info to still log things.

console.log = function(...args) {
   alert("logged")
   console.info(...args);
}

I recommend forking the NPM package instead and implementing your own logic.

CodePudding user response:

Override the global console's log method with a method named log that you define:

var previous = console.log;
console.log = function() {
    // Do whatever you need here:
    // call your own function with the original arguments
    yourFunction.apply(thisObj, arguments);
 
    // do the normal console.log if you want
    previous.apply(thisObj, arguments);
};
  • Related