Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Error URL.createObjectURL() not a function

I am trying to create a chrome extension that downloads a file with text inside. Some examples for doing this I've seen need to create a URL to pass to

chrome.downloads.download({ url: url, filename: fileName, conflictAction: 'overwrite', saveAs: false });

However, when I try to use URL.createUrlObject(), I get a type error

var blob = new Blob([textFile], {type: 'application/octet-binary'}); var url = URL.createObjectURL(blob);

I am using manifest v3

like image 797
Viv Avatar asked Mar 16 '26 22:03

Viv


1 Answers

    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;
  }
});

hope this can help someone else.

like image 72
Rezero Avatar answered Mar 24 '26 18:03

Rezero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!