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 http://tampermonkey.net/
// @version 0.2
// @description try to take over the world!
// @author You
// @match https://example.com
// @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 https://example.com/
, 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.
2
Answers
Well, I've solved the issue. Here's the revised script:
Also, a side note: I shouldn't do
console.log(logs);
, since it would be trapped to the loop of the log call itself. Justlogs
in the devtools console is enough.try
unsafewindow.console.log('print my data')
i am also attaching the link for reference tamper monkey unsafewindow ref