Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing into file using JavaScript/GreaseMonkey

I have captured list of data from the page using Greasemonkey.

GM Script

var hit = GM_getValue("hit") || 0;
var _url = "http://localhost:8080/test?p=$$pageNo$$";
_url = _url.replace("$$pageNo$$", hit);
GM_setValue("hit", ++hit); 
if(hit <= 100) {
window.location.href = _url;
}

This script will runs for nth time and capture <10K data, now i facing the issue in storing the captured data in some file. Anyone has any idea about how we can store the captured data into file/repo?

Thanks - Viswanathan G

like image 757
iamjustcoder Avatar asked Jun 17 '11 21:06

iamjustcoder


3 Answers

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.

like image 156
foolo Avatar answered Nov 06 '22 16:11

foolo


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 !

like image 41
Ismael EL ATIFI Avatar answered Nov 06 '22 16:11

Ismael EL ATIFI


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.

like image 14
ironchefpython Avatar answered Nov 06 '22 14:11

ironchefpython