Save File using Greasemonkey

前端 未结 6 2120
面向向阳花
面向向阳花 2020-12-09 04:21

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?

6条回答
  •  我在风中等你
    2020-12-09 04:51

    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:

    • http://jsfiddle.net/UselessCode/qm5AG/
    • How to create .txt file using JavaScript / HTML5?

    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.

提交回复
热议问题