javascriptfirefoxtampermonkey

TamperMonkey log to local file


While developing a userscript for tampermonkey, how can I have it write logs to local files on my machine?

I want the userscript to run when visiting a website, e.g. stackoverflow.com, then I want the running userscript to store its logs permanently (e.g. in a file on my disk) instead of in the browser console that only lasts as long as the tab does.


Solution

  • I ended up using GM_setValue, GM_getValue, & co. as suggested in comments.

    You need to grant them in the preamble:

    // @grant GM_setValue
    // @grant GM_getValue
    // @grant GM_listValues
    // @grant GM_deleteValue
    

    I used this function to download a file to disk on button click:

    var saveData = (function () {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        return function (data, fileName) {
            var blob = new Blob([data], {type: "octet/stream"});
            var url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        };
    }());
    
    let logs = GM_getValue('logs', null);
    if (logs != null) {
        saveData(logs.join('\n'), 'logs.txt');
    } else {
        alert('empty storage!');
    }