Extension API Callback Parameters, Event Handlers, and Messaging
How Chrome extension and platform APIs define callback parameters: signatures, optional handlers, events, and sendResponse patterns.
This page summarises how Chrome documents the callback parameter across extension APIs (Manifest V3 browser.* namespaces and Manifest V2 chrome.* references), plus a few related web-platform APIs in the same documentation set. Across dozens of modules—from storage to devtools.network—the same idea repeats: you pass a function that the browser invokes when an operation finishes or when an event fires, with arguments typed to match that moment.
callback parameter: what extension APIs mean by it
Section titled “callback parameter: what extension APIs mean by it”A callback parameter is a JavaScript function the API calls later with result or event data. In the reference pages, it is consistently documented as function, followed by the exact signature, for example (alarm: Alarm) => void on browser.alarms and the matching chrome.alarms MV2 page.
That pattern answers the everyday question “what will my function receive?”: open the method or event on the API you use and copy the documented parameter list—notificationId and buttonIndex for notification button clicks on browser.notifications, or (changes: object, areaName: string) => void when storage reports updates.
browser.* and chrome.*: same callback idea, different namespaces
Section titled “browser.* and chrome.*: same callback idea, different namespaces”Manifest V3 extension code is documented under browser.* (see browser.runtime). Legacy MV2 snippets use chrome.* (see chrome.runtime). Callback shapes for equivalent features are often identical: storage change listeners use (changes: object, areaName: string) => void on both browser.storage and chrome.storage, and on StorageArea / MV2 StorageArea with (changes: object) => void for area-specific callbacks.
Use one namespace consistently in a project (browser with a module bundler and chrome in older samples). The callback contract—argument types and order—is what must match the reference, not the global name.
optional callback vs required callback
Section titled “optional callback vs required callback”Some APIs treat the handler as optional. On chrome.devtools.panels (MV2) and browser.devtools.panels (MV3), setOpenResourceHandler is documented as:
Specifies the function to be called when the user clicks a resource link in the Developer Tools window. To unset the handler, either call the method with no parameters or pass null as the parameter.
— Chrome, chrome.devtools.panels
The optional handler receives (resource: Resource, lineNumber: number) => void, with resource described as a devtools.inspectedWindow Resource for the clicked link. A separate optional callback on the same module uses (theme: Theme) => void for DevTools theme changes.
Elsewhere, callbacks are required for event subscriptions—for example (newState: IdleState) => void on browser.idle, or proxy error details on browser.proxy where the callback receives an object with error, fatal, and nested details strings.
| Situation | Typical documentation | Example in cluster |
|---|---|---|
| One-shot async result | callback: function with typed args |
browser.history (result: HistoryItem) => void |
| Long-lived event | callback on on* listener |
browser.windows (window: Window) => void |
| Optional registration | callback marked optional; unset with null |
browser.devtools.panels setOpenResourceHandler |
| Registration with extra fields | Other parameters before callback |
chrome.gcm register with senderIds and optional (registrationId: string) => void |
Event listener callbacks: what each API passes
Section titled “Event listener callbacks: what each API passes”Event listener callbacks are still named callback in the reference, but they fire multiple times. The cluster shows the diversity of payloads you must handle:
- Runtime messaging — browser.runtime documents
(message: any, sender: MessageSender, sendResponse: function) => boolean | undefined, withsendResponseshaped as(response?: any) => void. The legacy chrome.extension message listener uses a similar triple withruntime.MessageSender. - Debugger — browser.debugger detach events use
(source: Debuggee, reason: DetachReason) => void; CDP traffic uses(source: DebuggerSession, method: string, params?: object) => void. - Omnibox — browser.omnibox includes a nested callback pattern:
(text: string, suggest: function) => voidwheresuggestaccepts(suggestResults: SuggestResult[]) => void. - GCM / FCM messages — browser.gcm message callbacks receive
message: objectwith optionalcollapseKey,data, andfrom; error callbacks receiveerrorwitherrorMessage, optionalmessageId, anddetails. - Input method engine — browser.input.ime includes rich objects such as
surroundingInfowithanchor,focus,offset, andtext(with notes thattextis only a subset around the cursor). - VPN provider — browser.vpnProvider mixes string ids,
ArrayBufferpacket data, and(event: UIEvent, id?: string) => voidfor UI events.
Design rule: one listener, one documented signature—do not assume all callback parameters share the same arity.
sendResponse: reply callback inside the message callback
Section titled “sendResponse: reply callback inside the message callback”For runtime.onMessage, the third parameter is itself a callback. Your listener may call sendResponse asynchronously only if you keep the message channel open; the reference documents returns boolean | undefined on the listener. Treat “return true when using sendResponse asynchronously” as standard extension folklore aligned with this signature; verify against the current browser.runtime event page when debugging missed replies.
Completion callbacks on individual methods
Section titled “Completion callbacks on individual methods”Not every callback is an event. Method-specific completion handlers include:
- browser.bookmarks move/reorder callbacks with
moveInfofields (index,oldIndex,oldParentId,parentId). - browser.printing job status via
(jobId: string, status: JobStatus) => void(MV2 chrome.printing also separates optionalcallbackon some methods). - browser.gcm
register-style flows on MV2 via chrome.gcm with up to 100senderIdsand optional(registrationId: string) => void. - chrome.webviewTag embedder callbacks for find results, load aborts, permission requests, and resize/zoom events—each with distinct parameter lists documented under
callback.
When migrating from callbacks to async/await, map each completion handler to the Promise-returning overload only after confirming that overload exists on the exact method you call.
Callbacks outside the extension reference (same documentation cluster)
Section titled “Callbacks outside the extension reference (same documentation cluster)”A few non-extension pages in the cluster use the same “pass a function, get called later” model:
- Compute Pressure — Compute Pressure API:
PressureObserver(callback)“will invoke a specified callback function when it detects that a change in the values of the source being observed has happened”; the callback receives an array of unreadPressureRecordobjects. - Workbox — workbox-core
registerQuotaErrorCallback(callback)adds a function executed on quota errors. - Cloudflare Workers WebSockets — WebSockets
addEventListener(event, callbackFunction)runs when aWebSocketEventoccurs. - Android Custom Tabs — Browser support
setEngagementSignalsCallback()“receive callbacks for events related to the user’s engagement with webpage within the tab.”
These are not interchangeable with extension callback parameters: argument types and lifetimes follow each API’s own reference.
Common mistakes when implementing callback parameters
Section titled “Common mistakes when implementing callback parameters”- Wrong argument order — Event callbacks are not always
(id, data); compare browser.management(id: string) => voidvs browser.certificateProvider request objects. - Ignoring optional vs omitted — DevTools resource handlers can be cleared by calling
setOpenResourceHandler()with no arguments ornullper browser.devtools.panels. - Nested callbacks — Omnibox
suggestmust be invoked withSuggestResult[]; failing to call it stalls the dropdown. - Message channel lifetime — Omitting
return truewhen using asynchronoussendResponseon browser.runtime listeners typically drops the response. - MV2 vs MV3 file paths — Reading chrome.storage while shipping MV3 can hide
browser.*permission or host changes documented only on the MV3 pages.
How to check this on your site
Section titled “How to check this on your site”- Load your extension unpacked and trigger the API or event you wired (for example a storage write and its
onChangedlistener). - In the service worker or background context, log inside the
callbackand confirm argument types match the reference for that method (compare with browser.runtime if the path involves messaging). - For DevTools extensions, click a resource link and confirm your browser.devtools.panels handler receives
resourceandlineNumber; unset withnulland confirm the default behavior returns. - For messaging, send a test message and verify
sendResponseis invoked before the channel closes, following the signature on browser.runtime. - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the official references, or you need a clarification on a specific callback signature, write to yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.