Skip to content

chrome.action.setIcon in an MV3 service worker: the OffscreenCanvas fix

6 min readModerok team

Why canvas code for chrome.action.setIcon fails in an MV3 service worker, the OffscreenCanvas fix, and the icon rules that still bite after it.

If you are drawing a dynamic toolbar icon and your code reaches for new Image() or document.createElement('canvas'), it will never run in a Manifest V3 service worker: there is no DOM there. Build the pixels with OffscreenCanvas instead and pass the result to chrome.action.setIcon:

// background.js, the MV3 service worker
async function setGreenIcon() {
  const canvas = new OffscreenCanvas(16, 16);
  const context = canvas.getContext('2d');
  context.clearRect(0, 0, 16, 16);
  context.fillStyle = '#00FF00';
  context.fillRect(0, 0, 16, 16);
  await chrome.action.setIcon({ imageData: context.getImageData(0, 0, 16, 16) });
}

That is Chrome's own recipe, almost line for line. The action reference, after describing a dynamically generated icon drawn with the HTML canvas element, adds the clause that matters: "or, if setting from an extension service worker, the offscreen canvas API."

Why the DOM version cannot work

Image(), per MDN, "creates a new HTMLImageElement instance", and document.createElement('canvas') returns an HTMLCanvasElement. Both are DOM elements, and Chrome's migrate to service workers guide states the constraint for the worker they would run in: "Because they can't access the DOM or the window interface, you'll need to move such calls to a different API or into an offscreen document." It is the same wall behind the error in Fix "document is not defined" in a Chrome extension service worker.

The three replacements are worker APIs:

  • OffscreenCanvas. MDN's page carries the note "This feature is available in Web Workers".
  • ImageData. MDN also marks it "available in Web Workers", and the same page notes that constructing one directly "is the most common way to create such an object in workers as createImageData() is not available there". Usually the 2D context's getImageData() hands you one instead.
  • createImageBitmap(). The worker version, WorkerGlobalScope.createImageBitmap(), "creates a bitmap from a given source" and is noted "only available in Web Workers". Its accepted sources include Blob, which is how a shipped PNG gets into the worker without an <img> tag.

The manifest setIcon needs

chrome.action is gated on the manifest. Chrome's reference, which now spells the namespace browser.action for the cross-browser form, states both requirements: "To use the browser.action API, specify a "manifest_version" of 3 and include the "action" key in your manifest file."

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0.0",
  "background": { "service_worker": "background.js" },
  "action": {
    "default_icon": {
      "16": "images/icon16.png",
      "32": "images/icon32.png"
    }
  }
}

The docs note that "Every extension has an icon in the Chrome toolbar, even if the "action" key isn't added to the manifest", but also recommend "that you always include at least the "action" and "default_icon" keys".

Starting from a PNG you already ship

A green square is a demo. Real icons are usually a shipped PNG with a count drawn on top, which means decoding a file in the worker. Chrome's action sample does it like this, under a comment noting the route "works in both extension pages and service workers".

async function iconDataFrom(file, size) {
  const response = await fetch(chrome.runtime.getURL(file));
  const blob = await response.blob();
  const bitmap = await createImageBitmap(blob);
  const canvas = new OffscreenCanvas(size, size);
  const context = canvas.getContext('2d');
  context.drawImage(bitmap, 0, 0, size, size);
  return context.getImageData(0, 0, size, size);
}

async function applyIconFile(file) {
  await chrome.action.setIcon({
    imageData: {
      16: await iconDataFrom(file, 16),
      32: await iconDataFrom(file, 32)
    }
  });
}

chrome.runtime.getURL() makes fetch resolve against your extension's own origin. If you only swap between images you already ship, skip the canvas: the icon "can be specified either as the path to an image file or as the pixel data from a canvas element", so chrome.action.setIcon({ path: 'images/icon16.png' }) is cheaper.

What still breaks after the fix

One ImageData means one size, and that size is 16. The reference spells out the default: "Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'16': foo}'". Icons "must be 16 device-independent pixels (DIPs) wide and tall", so on a 2x display a lone 16 pixel bitmap is scaled up and looks soft. Supply a dictionary, as above, and Chrome picks by pixel density.

The change is global unless you scope it. "If the tabId property is left out, the setting is treated as a global setting. Tab-specific settings take priority over global settings." The per-tab form has a documented expiry: tabId "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed."

Treat the icon as derived state. Your worker is killed on idle and the globals you drew from die with it, the lifecycle in Why your Chrome extension service worker keeps stopping. Nothing in your worker's memory is still there to redraw from on the next wake, so keep the value in chrome.storage.local and reapply it from top-level listeners:

chrome.runtime.onStartup.addListener(() => void applyStoredIcon());
chrome.runtime.onInstalled.addListener(() => void applyStoredIcon());

async function applyStoredIcon() {
  const { iconState } = await chrome.storage.local.get('iconState');
  if (!iconState) {
    const manifest = chrome.runtime.getManifest();
    await chrome.action.setIcon({ path: manifest.action.default_icon });
    return;
  }
  await applyIconFile(iconState.file);
}

Resetting through chrome.runtime.getManifest().action.default_icon is the sample's own reset path, and saves hardcoding filenames twice. Note where the drawing work lives: inside applyStoredIcon, with the two addListener calls above it at the top level. Chrome's service worker events guide is strict about that placement: "Event handlers in service workers need to be declared in the global scope, meaning they should be at the top level of the script and not be nested inside functions. This ensures that they are registered synchronously on initial script execution, which enables Chrome to dispatch events to the service worker as soon as it starts."

No SVG, and no animation. For packed extensions, "images can be in most formats that the Blink rendering engine can display, including PNG, JPEG, BMP, ICO, and others. SVG isn't supported." Unpacked ones are stricter: "Unpacked extensions must use PNG images." The docs also close the door on the clever version: "The action.setIcon() API is intended to set a static image. Don't use animated images for your icons."

Failures are quiet. setIcon() is documented as returning Promise<void> (Chrome 96+), and Chrome's snippet shows the older callback form. The chain above has several places to fail, a renamed image file among them. If you neither await the promise nor check chrome.runtime.lastError in the callback form, nothing in your code finds out that the update failed, and the toolbar is not where the difference shows up.

Firefox differences

Firefox never needed this workaround, which is why ported code can look fine there and break in Chrome. Firefox MV3 extensions use event pages, and MDN's background scripts page says they "run in the context of a special page called a background page. This gives them a window global, along with all the standard DOM APIs provided by that object." So document.createElement('canvas') works in a Firefox event page and fails in a Chrome service worker, and OffscreenCanvas is the one of the two that does not depend on which background you landed in.

Two API differences matter. MDN's action.setIcon() documents a windowId property that Chrome's setIcon parameters do not include, with the caveat "If windowId and tabId are both supplied, the function fails and the icon is not set", and words the tab-scoped reset differently from Chrome: "The icon is reset when the user navigates this tab to a new page." And where Chrome says SVG is not supported, MDN's action manifest page tells Firefox developers both that "You can supply a single icon as an SVG file, and it will be scaled correctly" and that you can "use a media query on prefers-color-scheme to update the icon for light and dark themes".

Catching the icon code that silently stopped working

A broken icon update is invisible in production, so the rejection is worth reporting rather than inferring from a support email. The Moderok SDK records uncaught exceptions and unhandled promise rejections as __error events in every context where you call Moderok.init(), and Moderok.captureError(error, props) covers the ones you catch yourself. The error tracking guide has the setup, including Moderok.captureLastError(apiName, lastError) for the callback form of setIcon.