Search code examples
javascripttampermonkey

Tampermonkey console.log doesn't seem to be the same as the one in chrome dev tools


This is what I have so far:

function loadScript(url) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script');
        script.onload = function() {
            resolve();
        };
        script.src = url;
        document.head.appendChild(script);
    });
};

loadScript("https://rawgit2.com/icodeforlove/template-colors-web/master/dist-browser/template-colors.js").then(load);

function load() {
    function logThing(pkt) {
        pkt = pkt.join(', ');
        console.log(c`${'['.red.bold}${pkt.green.bold}${']'.red.bold}`);
    };
    logThing(["Test", "thing", "here"]);
}

Normally, in dev tools console, it would log like this: enter image description here

But with tampermonkey it logs this: enter image description here

Why does tampermonkey do this? And how on earth do I fix this?

Also keep in mind, not using console.log looks like this: enter image description here


Solution

  • Load the script using @require instead:

    // ==UserScript==
    // @name         StackOverflow question 66604679
    // @version      0.1
    // @author       Wolfy
    // @match        https://stackoverflow.com/questions/66604679/tampermonkey-console-log-doesnt-seem-to-be-the-same-as-the-one-in-chrome-dev-to
    // @require      https://rawgit2.com/icodeforlove/template-colors-web/master/dist-browser/template-colors.js
    // @grant        none
    // ==/UserScript==
    /* globals c */
    
    (function() {    
      function logThing(wordsArray) {
        const stringToPrint = wordsArray.join(',');
        console.log(c`${'['.red.bold}${stringToPrint.green.bold}${']'.red.bold}`);
      }
      logThing(['Test', 'thing', 'here']);
    })();
    

    The reason is that in your script, the <script> is added at page context, so it doesn't patch TM's console.