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

旧街凉风 提交于 2019-12-18 12:35:41

问题


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 straight JS, but perhaps Chrome gives me some elevated privileges?


回答1:


You can now use HTML5 File API to download a file. It is still in development, but you can use a BlobBuilder and redirect your use to download that file:

var bb = new BlobBuilder();
bb.append(csvContents);
var blob = bb.getBlob(); 
location.href = window.webkitURL.createObjectURL(blob);

For more information regarding the File API, HTML5Rocks has a great tutorial:

http://www.html5rocks.com/tutorials/file/filesystem/




回答2:


Chrome doesn't provide any help with this, but I think you should be able to trigger a file save dialog using downloadify js library which uses a flash component behind the scenes.




回答3:


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"]


来源:https://stackoverflow.com/questions/4771758/how-to-generate-a-file-for-download-in-a-google-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!