How to generate a file for download in a Google Chrome Extension?

后端 未结 3 521
长情又很酷
长情又很酷 2020-12-29 15:33

I want to generate a CSV file as the result of some user interactions and then prompt the user to download it. How can I do that?

I don\'t think it\'s possible in st

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 16:14

    I needed to do exactly the same recently - generating file and enforcing its download in Chrome extension. Here you are a code snippet doing that, using ES6 and the recommended methods:

    let docContent = ... /* your content */;
    let doc = URL.createObjectURL( new Blob([docContent], {type: 'application/octet-binary'}) );
    chrome.downloads.download({ url: doc, filename: filename, conflictAction: 'overwrite', saveAs: true });
    

    You also have to declare a proper privilege in manifest.json:

    "permissions" : ["downloads"]
    

提交回复
热议问题