使用Greasemonkey保存文件

Kri*_*son 13 javascript greasemonkey

我有一些屏幕抓取表格数据,我想导出到CSV文件(目前我只是将它放在剪贴板中),无论如何在Greasemonkey中执行此操作?有关在何处查找样本或有关此类功能的文档的任何建议?

为了清楚起见,我不想写入本地文件系统(我知道在沙盒中是不可能的),但是提供一个可下载的文件 - 这也许是不可能的......

Rub*_*Rub 9

是的,你可以使用BLOB来做到这一点.

该脚本将内容附加到链接,该链接在单击时将提供下载文件(从不存在的文件).

更多信息:


这就是我做的方式(还有很多其他方法):

  1. GM(greasemonkey)脚本生成文件的内容
  2. GM使用sessionStorage.variable ="... content .."将其传递到网页
  3. 页面中的脚本使链接可见,并将变量的内容附加到BLOB对象.

您需要对对象进行字符串化/解析.

  • 触点= JSON.parse(sessionStorage.contacts)
  • sessionStorage.contacts = JSON.stringify(触点);

我略微修改了原始脚本,使其成为多个mime类型的通用.

这是我的.

// Stuff to create the BLOB object   --- ANY TYPE ---
var textFile = null,
//-- Function
makeTextFile = function (text,textType) {
    // textType can be  'text/html'  'text/vcard' 'text/txt'  ...
    var data = new Blob([text], {type: textType });
    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }
    textFile = window.URL.createObjectURL(data);
    return textFile;
  };
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


zan*_*etu 8

var data='col1,col2\nval1,val2';
var a = document.createElement('a');
a.href = 'data:application/csv;charset=utf-8,' + encodeURIComponent(data);
//supported by chrome 14+ and firefox 20+
a.download = 'data.csv';
//needed for firefox
document.getElementsByTagName('body')[0].appendChild(a);
//supported by chrome 20+ and firefox 5+
a.click();
Run Code Online (Sandbox Code Playgroud)

DEMO


Ryl*_*ley 3

也许您无法将其写入本地 CSV,但您也许可以将其写入Google 电子表格