Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Extension API Events: Listener Registration, Messaging, and Handler Rules

How browser extension API events work, when to use addListener, and special rules for downloads, cookies, tabs, and deprecated handlers.

This page summarises Chrome for Developers documentation on extension API events: registering callbacks with addListener, reacting to browser and user activity, and APIs where the platform imposes extra rules on listeners. The same patterns appear under the browser.* namespace (cross-browser extensions) and the chrome.* namespace (Chrome-specific and many legacy paths). A smaller set of chrome.app.* and Chrome Apps platform APIs (for example Bluetooth and sync file storage) use the same event model.

Extension API events: what addListener is for

Section titled “Extension API events: what addListener is for”

Extension API events notify your background context, popup, or DevTools page when something changes—user input, tab updates, storage writes, or incoming messages. You subscribe by calling namespace.eventName.addListener(callback) on the matching API object, documented per API on developer.chrome.com.

People often search for “extension event listener”, “chrome.runtime.onMessage”, or “when does this event fire”. In documentation terms, each event is a named channel; addListener registers a function that runs when the browser dispatches that event. Multiple extensions can listen to the same global event (bookmarks, cookies, history), but some events are scoped to your extension only (printing job status, VPN packets you own).

Fired when a message is sent from either runtime.sendMessage or tabs.sendMessage.

— Chrome for Developers, browser.runtime API — onMessage

For cross-part messaging, runtime.onConnect fires when a port is opened via runtime.connect, and runtime.onMessage handles one-shot messages. Older MV2-only paths such as chrome.extension.onRequest are deprecated in favour of runtime.onMessage.

browser.* vs chrome.*: same events, different entry points

Section titled “browser.* vs chrome.*: same events, different entry points”

Modern extension docs describe the browser.* namespace (also available as chrome.* in Chrome). Event names and semantics are usually identical; your choice is mainly manifest version, polyfill, and which reference page you follow.

Area Typical browser.* reference Parallel chrome.* (often MV2 doc path)
Tabs browser.tabs chrome.tabs
Storage browser.storage chrome.storage
Cookies browser.cookies chrome.cookies

Chrome Apps and some OS-level features remain under namespaces such as chrome.bluetooth, chrome.serial, and chrome.syncFileSystem—still using addListener, but requiring the app-capable manifest and permissions those pages describe.

User and UI events: clicks, commands, and omnibox input

Section titled “User and UI events: clicks, commands, and omnibox input”

browser.action.onClicked runs when the user clicks the extension’s toolbar action. The platform does not fire it if the action has a popup configured—the popup consumes the click. The legacy MV2 chrome.pageAction.onClicked follows the same rule for page actions.

browser.contextMenus.onClicked fires when the user chooses an item your extension registered.

keyboard shortcuts and address bar keywords

Section titled “keyboard shortcuts and address bar keywords”

browser.commands.onCommand fires when the user activates a registered command shortcut.

The browser.omnibox API exposes a full input session: onInputStarted (once per session, before onInputChanged), onInputEntered when the user accepts text, and onInputCancelled when they abandon the session. onDeleteSuggestion reports removal of a suggested result.

browser.notifications separates button clicks (onButtonClicked), body clicks (onClicked), and dismissals (onClosed). onShowSettings is deprecated since Chrome 65; custom notification settings links are no longer supported.

browser.tabs.onActivated fires when the active tab in a window changes. The tab’s URL may not be set yet at dispatch time; the documentation directs you to onUpdated for URL and other property updates. The same caveat applies to onCreated for URL and tab group membership.

Moving tabs between windows produces onDetached / onAttached rather than onMoved across windows. onReplaced covers prerender or instant replacement.

browser.windows.onFocusChanged returns chrome.windows.WINDOW_ID_NONE when no Chrome window is focused; on some Linux window managers, WINDOW_ID_NONE may appear immediately before switching between Chrome windows. onBoundsChanged (Chrome 86+) fires when resized bounds are committed, not during in-progress drags.

browser.sessions.onChanged tracks recently closed tabs and windows but does not monitor synced session changes.

browser.storage.onChanged monitors changes across storage areas. The storage API overview states that the onChanged event lets you monitor changes to a StorageArea.

cookies.onChanged and the overwrite two-step

Section titled “cookies.onChanged and the overwrite two-step”

browser.cookies.onChanged fires when a cookie is set or removed. Updating properties is implemented as removal then write:

the cookie to be updated is first removed entirely, generating a notification with “cause” of “overwrite” . Afterwards, a new cookie is written with the updated values, generating a second notification with “cause” “explicit”.

— Chrome for Developers, browser.cookies — onChanged

Handlers that deduplicate or count changes must treat one logical update as two events.

browser.declarativeNetRequest.onRuleMatchedDebug fires when a rule matches a request. It is only available for unpacked extensions with the "declarativeNetRequestFeedback" permission and is intended for debugging.

browser.history.onVisited runs before the page has loaded, with a HistoryItem for the URL.

Listeners with platform contracts (not “fire and forget”)

Section titled “Listeners with platform contracts (not “fire and forget”)”

downloads.onDeterminingFilename and suggest()

Section titled “downloads.onDeterminingFilename and suggest()”

During filename determination, browser.downloads.onDeterminingFilename lets an extension override DownloadItem.filename. Rules from the reference:

  • At most one listener per extension for this event.
  • The listener must call suggest exactly once, sync or async; async handlers must return true.
  • The download does not complete until all listeners have called suggest.
  • If several extensions override the name, the last installed extension that passes a suggestion object wins.

Prefer passing filename to download() when the name is known early.

On Chrome OS, browser.input.ime implements a custom IME. onKeyEvent is sent only if your extension owns the active IME; return true if handled, false if not. For async handling, return undefined and later call keyEventHandled() with the result.

onSurroundingTextChanged limits surrounding text to 100 characters in each direction from the caret.

webAuthenticationProxy: register at load time

Section titled “webAuthenticationProxy: register at load time”

browser.webAuthenticationProxy.onRemoteSessionStateChange can be triggered when a native host touches a file under WebAuthenticationProxyRemoteSessionStateChange in the user data directory (empty file contents suffice). The listener must be registered synchronously at load time. onRequestCanceled means the extension cannot complete that WebAuthn request anymore.

During import, browser.bookmarks.onImportBegan signals that expensive observers should ignore onCreated until onImportEnded; other bookmark events should still be handled.

browser.gcm exposes onMessage, onMessagesDeleted, and onSendError for FCM lifecycle issues.

browser.idle.onStateChanged reports active, idle, or locked (screen lock or screensaver).

DevTools extension pages use separate namespaces, for example browser.devtools.network.onRequestFinished when a request’s data is fully available, and browser.devtools.inspectedWindow.onResourceContentCommitted when the user saves an edited resource.

browser.debugger.onDetach fires when debugging ends because the tab closed or DevTools attached to that tab. onEvent forwards instrumentation events from the target.

browser.processes.onUpdatedWithMemory matches onUpdated but adds memory stats; the docs note extra CPU cost, so subscribe only when needed.

Event Guidance
browser.runtime.onBrowserUpdateAvailable Deprecated; use runtime.onRestartRequired
chrome.extension.onRequest / onRequestExternal Use runtime.onMessage / runtime.onMessageExternal
chrome.tabs.onActiveChanged / onSelectionChanged / onHighlightChanged Use tabs.onActivated / onHighlighted
browser.notifications.onShowSettings Deprecated since Chrome 65

browser.runtime.onSuspendCanceled is sent after onSuspend if the extension will not be unloaded after all—relevant for event-page style lifecycles.

Chrome Apps and device APIs (same listener pattern)

Section titled “Chrome Apps and device APIs (same listener pattern)”

Packaged apps listen for hardware and connectivity changes with the same addListener pattern, for example chrome.bluetooth.onAdapterStateChanged for adapter power state (see also the Chrome Apps Bluetooth guide), chrome.bluetoothLowEnergy.onCharacteristicValueChanged when notifications are enabled, and socket events on chrome.sockets.tcp / chrome.bluetoothSocket.

chrome.syncFileSystem.onFileStatusChanged reports sync status transitions (synced, conflicting, and so on); the Storage APIs guide walks through handling remote_to_local additions and manual conflict detachment.

chrome.vpnProvider and browser.vpnProvider tunnel events such as onPacketReceived apply only to VPN sessions owned by the extension.

Common mistakes when using event listeners

Section titled “Common mistakes when using event listeners”
  • Assuming complete tab or window data on the first event—pair onActivated / onCreated with tabs.onUpdated.
  • Treating cookie updates as a single onChanged notification.
  • Registering multiple downloads.onDeterminingFilename listeners or forgetting to call suggest().
  • Expecting action.onClicked while a popup is configured.
  • Using onRuleMatchedDebug in a packed production build without the debug permission.
  • Subscribing to processes.onUpdatedWithMemory continuously without need.
  • Relying on sessions.onChanged for synced session state across devices.
  • Missing synchronous registration for webAuthenticationProxy remote session events.
  1. Identify the event in the matching API reference (for example browser.tabs or browser.runtime) and confirm required manifest permissions and MV3 service worker constraints.

  2. Load your extension as an unpacked build, open the service worker or background inspector, and register addListener with logging that prints event names and payloads.

  3. Trigger the user or system action described in the reference (tab switch, cookie write, omnibox keyword session, download, and so on) and confirm the callback runs with the documented fields—especially timing notes such as history firing before load.

  4. For special-contract events (downloads.onDeterminingFilename, input.ime.onKeyEvent, webAuthenticationProxy), step through one success and one cancellation path and verify suggest, return values, or onRequestCanceled behaviour.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page does not match the behaviour you see in Chrome, email yimasynthetic@gmail.com with the page URL and the exact sentence or event name you are questioning, and we will clarify or correct it.