Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

javascript - Save File using Greasemonkey

I have some screen scraped tabular data that I want to export to a CSV file (currently I am just placing it in the clipboard), is there anyway to do this in Greasemonkey? Any suggestions on where to look for a sample or some documentation on this kind of functionality?

Just to be clear, I don't want to write to the local file system (I know that is impossible in the sandbox), but present a downloadable file - which may also be impossible...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can do it using BLOB.

The script will attach content to a link that when clicked will offer to download a file (a file that never existed).

More info on:


This is how I did it (there are many other ways to do it):

  1. GM (greasemonkey) script generates the content of the file
  2. GM passes it to the web page using sessionStorage.variable="...content.."
  3. script within page makes link visible and attach the content of the variable to the BLOB object.

You many need to stringify / parse the object.

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

I modified slightly the original script to make it generic for multiple mime types.

Here is mine.

// 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;
  };

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...