使用JavaScript/GreaseMonkey存储到文件中

iam*_*der 10 javascript greasemonkey

我使用Greasemonkey从页面中捕获了数据列表.

GM脚本

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;
}
Run Code Online (Sandbox Code Playgroud)

此脚本将运行第n次并捕获<10K数据,现在我面临将捕获的数据存储在某个文件中的问题.任何人都知道我们如何将捕获的数据存储到文件/仓库?

谢谢 - Viswanathan G.

iro*_*hon 13

不,不能把它写到文件中,但是如果你真的很无聊,可以将它发布到http://pastebin.com(或任何其他接受带有大量数据的POST请求的URL).

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");
  }
});
Run Code Online (Sandbox Code Playgroud)

请注意,您需要有一个pastebin帐户才能使用该API.


如果您确实需要将文件写入本地文件系统,请在桌面上运行Web服务器,然后将http PUT请求的结果保存到磁盘.


Ism*_*IFI 8

一个非常快速和简单的解决方案是使用FileSaver.js:
1)将以下行添加到Greasemonkey脚本的== UserScript ==部分

// @require     https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js
Run Code Online (Sandbox Code Playgroud)

2)将以下两行代码添加到GM脚本中

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

saveAs(blob, "hello world.txt");
Run Code Online (Sandbox Code Playgroud)


此代码示例将显示一个对话框,用于下载名为"hello world.txt"的文件,其中包含文本"Hello,world!".只需用您选择的文件名和文本内容替换它!

  • 相同的结果,但你最好得到 `// @require https://raw.githubusercontent.com/eligrey/FileSaver.js/master/dist/FileSaver.js` (4认同)

foo*_*olo 8

我使用这个技巧从 Tampermonkey 脚本下载文件:

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);
    };
}());
Run Code Online (Sandbox Code Playgroud)

然后用以下方式调用它:

saveData("this data will be written in the file", "file.txt");
Run Code Online (Sandbox Code Playgroud)

它的工作原理是创建一个隐藏元素并模拟该元素被单击。其行为就像用户单击下载链接一样,因此浏览器将下载该文件,并保存在浏览器放置下载文件的任何位置。