Skip to content

Instantly share code, notes, and snippets.

@tkrkt
Created April 5, 2018 03:46
Show Gist options
  • Save tkrkt/44949fe3f0cac2040c3ce3004fe1fe9c to your computer and use it in GitHub Desktop.
Save tkrkt/44949fe3f0cac2040c3ce3004fe1fe9c to your computer and use it in GitHub Desktop.
How to download files on WebExtension
// Use an A tag
// Firefox: OK, Chrome: NG
// Waiting with setTimeout is dirty
const downloadWithATag = (filename, text) => {
const blob = new Blob([text], {type: 'text/plain;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
Object.assign(a.style, {
visibility: 'hidden',
width: 0,
height: 0,
overflow: 'hidden',
position: 'absolute'
});
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 10000); // <= dirty!
};
// Use browser.downloads API (requires "downloads" permission)
// Firefox: OK, Chrome: OK
// Either way it is dirty
let handlers = []; // Array<{id: string, url: string}>
browser.downloads.onChanged.addListener((delta) => {
const handler = hanlders.find(h => h.id === delta.id);
if (hanlder && delta.state) {
if (delta.state.current === 'complete' || delta.state.current === 'interrupted') {
URL.revokeObjectURL(handler.url);
handlers = handlers.filter(h => h.id !== handler.id);
}
}
});
const downloadWithBrowserAPI = (filename, text) => {
const text = 'sample text';
const blob = new Blob([text], {type: 'text/plain;charset=utf-8'});
const url = URL.createObjectURL(blob);
browser.downloads.download({filename, url}, (id) => {
handlers.push({id, url});
});
};
// Is revokeObjectURL really necessary?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment