console.log override not working in Tampermonkey

I made the following Tampermonkey userscript for testing, it’s supposed to be worked as commented, but it doesn’t.

// ==UserScript==
// @name         Test: overriding console.log
// @namespace
// @version      0.2
// @description  try to take over the world!
// @author       You
// @match

// @run-at       document-idle
// @noframes
// ==/UserScript==

var consoleLog = console.log;
var logs = [];
console.log = function(message) { // Override the console.log function to capture the output
  logs.push(message);  // Store the message in the logs array
  consoleLog.apply(console, ["[Test App] ", ...arguments]);  // Call the original console.log function
console.log('Hello, world!'); // this would log `[Test App] Hello, world!`
// console.log = consoleLog; // Restore the original console.log function
console.log(logs); // this would log `["Hello, world!"]`

So, going to, opens devtools console tab, I see:

Hello, world!

But, it’s supposed to be something as follows:

[Test App] Hello, world!
["Hello, world!"]

The fact is that it works fine on node.js or on the chrome devtools console, so I’m confused with the weird behavior. So, how to fix? Thanks.

>Solution :

enter image description here

try unsafewindow.console.log('print my data') i am also attaching the link for reference tamper monkey unsafewindow ref

Leave a Reply