TypeError: Error URL.createObjectURL() not a function
Asked Answered
U

2

8

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

Uveitis answered 25/6, 2021 at 22:43 Comment(5)
createObjectURL is not allowed in a service worker so just use a data URL e.g. 'data:text/plain,' + textFile.replace(/#/g, '%23')Selfcontradiction
crbug.com/1224027Selfcontradiction
@wOxxOm, i'm new to js and chrome extension development, i'm having the same issue and couldn't figure out how to fix it. tried to create data uri using chrome.window.btoa, which is also throwing error. could you please post the solution here as an answer?Lungki
Use btoa instead of chrome.window.btoa. Ask a new question for further assistance if necessary.Selfcontradiction
For further explanation about what URL.createObjectURL does and why it is not allowed in Service Workers.Whiny
B
4

    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.

Butterfat answered 6/5, 2023 at 7:17 Comment(0)
F
0

a mi me funciono de esta manera:

 const binary = 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, 
        });
Fluky answered 27/12, 2023 at 21:7 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Bloemfontein
Personally I would re-use codigoBase64 instead of btoa(binary).Whiny

© 2022 - 2024 — McMap. All rights reserved.