我正在尝试创建一个 chrome 扩展来下载包含文本的文件。我见过一些这样做的例子,需要创建一个 URL 来传递给
chrome.downloads.download({ url: url, filename: fileName, conflictAction: 'overwrite', saveAs: false });
但是,当我尝试使用 URL.createUrlObject() 时,出现类型错误
var blob = new Blob([textFile], {type: 'application/octet-binary'}); var url = URL.createObjectURL(blob);
我正在使用清单v3
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === "saveCSV") {
// for utf8 bom
const data = '\uFEFF' + request.data;
const blob = new Blob([data], { type: "text/csv;charset=utf-8" });
// use BlobReader object to read Blob data
const reader = new FileReader();
reader.onload = () => {
const buffer = reader.result;
const blobUrl = `data:${blob.type};base64,${btoa(new Uint8Array(buffer).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`;
chrome.downloads.download({
url: blobUrl,
filename: request.filename,
saveAs: true,
conflictAction: "uniquify"
}, () => {
sendResponse({ success: true });
});
};
reader.readAsArrayBuffer(blob);
return true;
}
});
希望这可以帮助别人。
const 二进制 = atob(codigoBase64);
const blob = new Blob([binary], { type: "application/pdf" });
const dataURL = `data:${blob.type};base64,${btoa(binary)}`;
chrome.downloads.download({
url: dataURL,
filename: `${nombreArchivo}`,
saveAs: true,
});