javascriptservice-workerchrome-extension-manifest-v3

How to use URL.createObjectURL inside a manifest v3 extension ServiceWorker


My extension creates zip archive with images inside. And I used chrome.downloads.download to download my archive to device.

const url = URL.createObjectURL(archiveBlob);

chrome.downloads.download({
  url,
  filename: `${archiveData.fileName}.zip`,
  saveAs: false
});

And also URL.createObjectURL required in my extension when I convert ArrayBuffer to Image

async bufferToImage(buffer: ArrayBuffer): Promise<InstanceType<typeof Image>> {
  return new Promise((res, rej) => {
    const blob = new Blob([buffer]);
    const objectURL = URL.createObjectURL(blob);
    const img = new Image();
    img.src = objectURL;
    img.onload = () => res(img);
  });
}

How can I do it now in Manifest v3 ServiceWorker?


Solution

  • You can convert Blob to base64.

    If you want export image:

    /**
     * capture and download
     * 截图并下载
     */
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    
      chrome.tabs.query({ active: true }, async (tabs) => {
        const tab = tabs[0];
        const image = await chrome.tabs.captureVisibleTab(tab.windowId, {
          format: "png",
        });
    
        chrome.downloads.download({
          url: image,
          filename: "1.png",
        })
    
      });
    });
    
    

    If you want export zip:

    import JSZip from "jszip";
    
    /**
     * example: captureVisibleTab and export zip
     * 案例:截图并导出zip
     */
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      chrome.tabs.query({ active: true }, async (tabs) => {
        const tab = tabs[0];
    
        // capture
        const image = await chrome.tabs.captureVisibleTab(tab.windowId, {
          format: "png",
        });
    
        // image base64 => blob
        const blob = await fetch(image).then((response) => response.blob());
    
        // zip image
        const zip = new JSZip();
        zip.file("insta-snap1.png", blob, { binary: true });
        const zipData = await zip.generateAsync({
          type: "base64",
        });
    
        // download zip with base64
        chrome.downloads.download({
          url: `data:application/octet-stream;base64,${zipData}`,
          filename: "test.zip",
        });
      });
    });