javascript 如何在WebExtension上下载文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 如何在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?
以上是关于javascript 如何在WebExtension上下载文件的主要内容,如果未能解决你的问题,请参考以下文章
javascript 如何在Javascript中替换_为空格?
javascript 你如何在JavaScript中找到调用函数?
如何在html代码里面调用javascript变量?
Javascript:如何在执行 javascript 代码之间设置一个简单的延迟?
javascript 如何获取后台的对象???
javascript 如何在Javascript中将字符串转换为数字?