Skip to content

Fix "URL.createObjectURL is not a function" in an MV3 service worker

8 min readModerok team

Why URL.createObjectURL is undefined in a Chrome MV3 extension service worker, the data: URL and offscreen document fixes, and what still breaks after.

URL.createObjectURL is not a function in a Manifest V3 extension service worker means what it says: the method is not there. URL exists and Blob exists, but object URL minting is not exposed to service workers, so there is nothing to patch and no permission to add. For a text or JSON export, skip the blob and hand chrome.downloads.download() a data: URL:

// sw.js
async function exportCsv() {
  const csv = "name,clicks\nfoo,3\n";
  return chrome.downloads.download({
    url: "data:text/csv;charset=utf-8," + encodeURIComponent(csv),
    filename: "export.csv",
  });
}

If you need a real blob URL, mint it in an offscreen document and message it back. Both paths are below, along with the part nobody warns you about: that URL dies with the document.

Why URL.createObjectURL is not a function here

This is a web platform rule, not an extension one. MDN's page for the method notes: "This feature is not available in Service Workers due to its potential to create memory leaks" (URL.createObjectURL() static method). The leak risk is the reason. MDN's page on the blob: scheme explains that "Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so" (blob: URLs). A service worker has no document whose unload could trigger that cleanup.

An MV3 extension background script is a service worker, so it inherits that. Chrome's offscreen API reference frames the gap the same way: service workers have no DOM access, and the Offscreen API lets an extension use DOM APIs in a hidden document.

What confuses people is how much does work. In an MV3 worker on Chrome 158, typeof Blob and typeof FileReader both report function, and blob.arrayBuffer() and new Response(blob).text() resolve normally. Only the two URL helpers are gone: typeof URL.createObjectURL and typeof URL.revokeObjectURL are both undefined. You can build and read a blob there, you just cannot turn one into a URL.

Fix 1: build a data: URL and never create a blob

For text you generate, the object URL was only ever a courier. A data: URL carries the same bytes with no document and no lifetime:

async function downloadText(text, mime, filename) {
  return chrome.downloads.download({
    url: `data:${mime};charset=utf-8,` + encodeURIComponent(text),
    filename,
  });
}

// binary, or anything you already hold as a Blob
async function downloadBlob(blob, filename) {
  const bytes = new Uint8Array(await blob.arrayBuffer());
  let binary = "";
  for (const b of bytes) binary += String.fromCharCode(b);
  return chrome.downloads.download({
    url: `data:${blob.type || "application/octet-stream"};base64,` + btoa(binary),
    filename,
  });
}

download() needs the "downloads" permission: "You must declare the "downloads" permission in the extension manifest to use this API" (chrome.downloads). The filename is "A file path relative to the Downloads directory", and the same reference warns that "Absolute paths, empty paths, and paths containing back-references ".." will cause an error". A hardcoded /tmp/export.csv gives Invalid filename on Chrome 158.

The limit here is memory, not any documented cap: base64 inflates the payload by roughly a third, encodeURIComponent can inflate it more, and the whole string sits in the worker's heap while Chrome copies it. In a local Chrome 158 test a 12 MB data: URL completed, which covers most CSV and JSON exports, but a several hundred megabyte export is not a data: URL job.

Fix 2: mint the blob URL in an offscreen document

When you genuinely need a blob: URL, the offscreen API covers it. Its reasons enum names the method: BLOBS is "Specifies that the offscreen document needs to interact with Blob objects (including URL.createObjectURL())." (chrome.offscreen).

{
  "manifest_version": 3,
  "name": "My extension",
  "version": "1.0.0",
  "permissions": ["downloads", "offscreen", "storage"],
  "background": { "service_worker": "sw.js" }
}
// offscreen.js, loaded by a static offscreen.html in your package
chrome.runtime.onMessage.addListener((msg, sender, respond) => {
  if (msg.type !== "make-blob-url") return;
  const blob = new Blob([msg.text], { type: msg.mime });
  respond({ url: URL.createObjectURL(blob) });
});
// sw.js
async function exportViaBlobUrl(csv) {
  const open = await chrome.runtime.getContexts({
    contextTypes: ["OFFSCREEN_DOCUMENT"],
  });
  if (open.length === 0) {
    await chrome.offscreen.createDocument({
      url: "offscreen.html",
      reasons: ["BLOBS"],
      justification: "Create a blob URL for a user-requested export",
    });
  }
  const { url } = await chrome.runtime.sendMessage({
    type: "make-blob-url",
    text: csv,
    mime: "text/csv",
  });
  const id = await chrome.downloads.download({ url, filename: "export.csv" });
  await chrome.storage.session.set({ exportDownloadId: id });
}

The getContexts() check covers sequential exports, not concurrent ones: two overlapping calls both see zero documents, and the second throws. The download call stays in the worker on purpose: an offscreen document cannot make it, because "The runtime API is the only extensions API supported by offscreen documents" (chrome.offscreen). The blob URL is same origin, so the worker passes it straight to downloads.download(). The offscreen document walkthrough covers the HTML file and the one-document rule.

Two error strings you will meet. A misremembered reason (it is BLOBS, plural) is rejected with the full enum: Value must be one of AUDIO_PLAYBACK, BATTERY_STATUS, BLOBS, CLIPBOARD, DISPLAY_MEDIA, DOM_PARSER, DOM_SCRAPING, GEOLOCATION, IFRAME_SCRIPTING, LOCAL_STORAGE, MATCH_MEDIA, TESTING, USER_MEDIA, WEB_RTC, WORKERS. A second createDocument() gives Only a single offscreen document may be created., matching the documented limit that "an installed extension can only have one open at a time" (chrome.offscreen).

What still breaks after the fix

The blob URL dies with the document, but a download already accepted does not. On Chrome 158 they measure differently, and the first half is a race. The URL outlives closeDocument() by only tens of milliseconds: fetched the instant that call resolves it still returns 200, and from roughly 50 ms on it is Failed to fetch. Hand it to download() 500 ms or 3 seconds after closing and every run ended state: "interrupted", error: "NETWORK_FAILED", zero bytes. Call download() first, though, and Chrome takes its own reference to the data: closing the document the moment that call resolves did not interrupt the transfer, including a 64 MB blob that finished roughly 300 ms after the document was gone. So the rule is narrow: never hold a blob URL across closeDocument(), but the document need not outlive the transfer.

download() resolving is not the file arriving. It resolves with a download id as soon as Chrome accepts the request. Failures land on the DownloadItem afterwards: "Errors relating to the network begin with NETWORK_, errors relating to the process of writing the file to the file system begin with FILE_, and interruptions initiated by the user begin with USER_" (chrome.downloads). chrome.downloads.onChanged is where you learn whether the file arrived, and the place to close the document once an export settles. Two details the obvious handler gets wrong: it belongs at the top level of the worker, not inside the export flow, because a worker that was asleep when the download finished only dispatches to listeners registered during the script's synchronous run; and closeDocument() rejects with No current offscreen document. if nothing is open.

// top level of sw.js, not inside the export flow
chrome.downloads.onChanged.addListener(async (delta) => {
  if (!delta.state) return;
  const { exportDownloadId } = await chrome.storage.session.get("exportDownloadId");
  if (delta.id !== exportDownloadId) return;
  if (delta.state.current !== "complete" && delta.state.current !== "interrupted") return;

  await chrome.storage.session.remove("exportDownloadId");
  try {
    await chrome.offscreen.closeDocument();
  } catch {
    // nothing open, which is fine
  }
});

onChanged hands you a DownloadDelta, where each changed field is an object with previous and current, not a bare value, hence delta.state.current above. For why it was interrupted, fetch the item with chrome.downloads.search({ id: delta.id }) and read item.error.

The worker can die mid flow. This is async work in a context Chrome can tear down, which is why the id lives in chrome.storage.session, not a closure. Our why a service worker keeps stopping covers that lifecycle.

Firefox differences

None of this applies in Firefox, for a structural reason. Firefox does not run extension background code as a service worker at all: per MDN's background key, "background.service_worker is not supported (see Firefox bug 1573659)", and "in Firefox, the scripts property is used, and an event page starts because Firefox only supports scripts for background scripts" (manifest.json/background). Those scripts run in a page: "If you specify scripts, an empty page is created where your scripts run" and "The scripts share the same window global context." A page has a document, so URL.createObjectURL is available and the error never appears.

There is also no offscreen API to fall back on. The offscreen namespace does not appear on MDN's Browser support for JavaScript APIs, and MDN's Chrome incompatibilities page says of that listing: "The Browser support for JavaScript APIs page includes compatibility tables for all APIs that have any support in Firefox." For one codebase in both, feature detect (typeof URL.createObjectURL === "function") or use data: URLs everywhere.

Firefox does add cleanup work, because nothing unloads for you. MDN's extension file guide: "If the URL was created in an extension's background page, this is not unloaded until the extension is disabled, uninstalled, or reloaded, so holding this memory unnecessarily could affect browser performance" (Working with files). Revoke, but not too early. MDN's downloads.download() page: "If you use URL.createObjectURL() to download data created in JavaScript and you want to revoke the object URL (with revokeObjectURL) later (as it is strongly recommended), you need to do that after the download has been completed. To do so, listen to the downloads.onChanged event" (downloads.download()). Same event as the Chrome offscreen teardown.

Seeing the failures you cannot reproduce

Export bugs get reported as "the button does nothing", because the failure is in a worker with no console attached. Moderok's SDK records uncaught exceptions and unhandled promise rejections as error events in any context where you call Moderok.init(). An interrupted download is neither, so record it in the handler above:

const [item] = await chrome.downloads.search({ id: delta.id });
if (item?.error) {
  Moderok.captureError(new Error("export download interrupted"), {
    action: "export_csv",
    reason: item.error,
  });
}

The real interrupt reason, NETWORK_FAILED or FILE_ACCESS_DENIED, then reaches your error logs rather than only a bug report saying the button is broken. Identical errors are deduped within a minute and bursts are rate limited, so treat the logs as signal, not a tally. The error tracking guide covers both paths.