Home > other >  How to get and store the console logged value in javascript
How to get and store the console logged value in javascript

Time:10-01

I am trying to get the console logged value

here is the code,

console.log('sample output');
var logBackup = console.log;
var logMessages = [];

console.log = function () {
  logMessages.push.apply(logMessages, arguments);
  logBackup.apply(console, arguments);
};

console.log('logged values here', logMessages);

but it's returning a recursion empty arrays,

enter image description here

is there any way to get the console logged value and display that on webpage

CodePudding user response:

Maybe something like this? Just a quick hack but the key is that I check that I don't add a reference of logMessages into logMessages itself, avoiding the circular reference.

console.log('sample output');
var logBackup = console.log;
var logMessages = [];

console.log = function (...argz) {
  pushArgz = argz.filter(a => a !== logMessages);
  logMessages.push(...pushArgz);
  logBackup.apply(console, argz);
};

console.log('logged values here', logMessages);
console.log('logged values here', logMessages);
console.log('logged values here', logMessages);

  • Related