How to download a PDF in a custom chrome extension using offscreen document

339 Views Asked by At

Because of the size of my generated PDF, the base64 conversion is not possible and I have to use the offscreen functionality.

Based on this answer -> https://stackoverflow.com/a/75539867/8016254

I tried to download a PDF file that will be reated in my custom chrome extension.

background.js

import './pdf-lib.min.js';

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    (async () => {
        if (message.pdfUrls && message.pdfUrls.length > 0) {
            // Debug PDF
            const urls = ["https://www.africau.edu/images/default/sample.pdf"];
            await mergeAllPDFs(urls, "Test");
        }
    })();

    return true;
});
async function mergeAllPDFs(urls, filename) {
    const numDocs = urls.length;
    const pdfDoc = await PDFLib.PDFDocument.create();
    for (let i = 0; i < numDocs; i++) {
        console.log(`Fetching ${urls[i]}`)
        const donorPdf = await fetch(urls[i]);
        const donorPdfBytes = await donorPdf.arrayBuffer();
        const donorPdfDoc = await PDFLib.PDFDocument.load(donorPdfBytes);
        const copiedPages = await pdfDoc.copyPages(donorPdfDoc, donorPdfDoc.getPageIndices());
        copiedPages.forEach((page) => pdfDoc.addPage(page));
    }
    const pdfDocBytes = await pdfDoc.save();
    const waiting = await chrome.offscreen.createDocument({
        url: 'offscreen.html',
        reasons: ['BLOBS'],
        justification: 'reason for needing the document',
    });
    chrome.runtime.sendMessage({
        data: pdfDocBytes
    }, (response) => {
        console.log(response);
        const url = response.url;
        console.log(url);
        chrome.downloads.download({
            url: url,
            filename: filename + ".pdf"
        });
    });

}

offscreen.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    const blob = new Blob([message.data], { type: "application/pdf" });
    const url = URL.createObjectURL(blob);
    sendResponse({ url: url });
    return true;
});

The resulting PDF seems to be corrupt and way smaller than expected. Any ideas?

1

There are 1 best solutions below

7
On BEST ANSWER

Problem: chrome.runtime.sendMessage can't send binary data in Chrome.

Solution: use standard web messaging.

// background

await chrome.offscreen.createDocument({url: 'offscreen.html', /*....*/});
const clientUrl = chrome.runtime.getURL('offscreen.html');
const client = (await clients.matchAll({includeUncontrolled: true}))
  .find(c => c.url === clientUrl);
const mc = new MessageChannel();
client.postMessage(blob, [mc.port2]);
const {data: blobUrl} = await new Promise(cb => (mc.port1.onmessage = cb));
chrome.downloads.download({
  url: blobUrl,
  filename: filename + '.pdf',
});

// offscreen.js

navigator.serviceWorker.onmessage = e => {
  e.ports[0].postMessage(URL.createObjectURL(e.data));
  setTimeout(close);
};