Storing into file using JavaScript/GreaseMonkey

I use this trick to download a file from a Tampermonkey script:

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);
    };
}());

Then call it with:

saveData("this data will be written in the file", "file.txt");

It works by creating a hidden element and simulating that element being clicked. It will behave as if the user clicked a download link, so the file will be downloaded by the browser, and saved wherever the browser puts downloaded files.


A very fast and easy solution is to use FileSaver.js :
1) Add the following line into the ==UserScript== section of your Greasemonkey script

// @require     https://raw.githubusercontent.com/eligrey/FileSaver.js/master/dist/FileSaver.min.js
  1. Add the 2 following lines of code to the GM script

    var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});

    saveAs(blob, "hello world.txt");
    This code example will display a dialog box to download a file named "hello world.txt" containing the text "Hello, world!". Just replace this by the file name and the text content of your choice !


Nope, can't write it to a file, but if you're really bored, you can post it to http://pastebin.com (or any other URL that accepts a POST request with a bunch of data).

GM_xmlhttpRequest({
  method: "POST",
  url: "http://pastebin.com/post.php",
  data: <your data here>,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  onload: function(response) {
    alert("posted");
  }
});

Note you need to have a pastebin account to use the API.


If you really need to write a file to your local filesystem, run a web server on your desktop, and then save the results of an http PUT request to disk.