skip to Main Content

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


  1. Chosen as BEST ANSWER

    Well, I've solved the issue. Here's the revised script:

    // ==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
    // @grant        unsafeWindow
    // ==/UserScript==
    
    var consoleLog = unsafeWindow.console.log;
    var logs = [];
    
    unsafeWindow.console.log = function(message) {
      logs.push(message);  
      consoleLog.apply(unsafeWindow.console, ["[Test App] ", ...arguments]);  
    };
    
    unsafeWindow.console.log('Hello, world!');
    // unsafeWindow.console.log(logs);
    

    The Tampermonkey environment operates in a sort of "sandbox", and some behaviors can be different from the regular JavaScript context.

    The idea here is to use unsafeWindow to reference the actual global window object in the page context, rather than the Tampermonkey sandboxed version of window.

    Also, a side note: I shouldn't do console.log(logs);, since it would be trapped to the loop of the log call itself. Just logs in the devtools console is enough.


  2. enter image description here

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search