Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Extension Network Request Lifecycle, Navigation Events, and Declarative Rules

How browser extension webRequest, webNavigation, and declarativeNetRequest observe pages, match traffic, and block or redirect requests.

This page summarises Google Chrome’s extension documentation for observing and influencing network traffic and in-flight navigation. Extension authors typically choose among the imperative webRequest API, the navigation-oriented webNavigation API, and the declarative declarativeNetRequest API—often together with filtered events so listeners run only for URLs and contexts they care about.

webRequest API: observe, block, and modify individual requests

Section titled “webRequest API: observe, block, and modify individual requests”

The webRequest API exposes events that follow the life cycle of a web request. You can use them to observe and analyse traffic; certain synchronous events let you intercept, block, or modify a request.

The web request API defines a set of events that follow the life cycle of a web request. You can use these events to observe and analyze traffic. Certain synchronous events will allow you to intercept, block, or modify a request.

— Chrome, webRequest API

webRequest event order: what fires before the network

Section titled “webRequest event order: what fires before the network”

For a successful request, Chrome documents this sequence:

  1. onBeforeRequest (optionally synchronous)—before any TCP connection; cancel or redirect.
  2. onBeforeSendHeaders (optionally synchronous)—initial headers prepared; modify or cancel.
  3. onSendHeaders—final request headers after all extensions; informational only.
  4. onHeadersReceived (optionally synchronous)—each time response headers arrive (redirects/auth can repeat); modify response headers, cancel, or redirect.
  5. onAuthRequired (optionally synchronous)—user authentication.
  6. onBeforeRedirect—redirect about to run; informational.
  7. onResponseStarted—first byte of body; informational.
  8. onCompleted or onErrorOccurred as the final event.

The web request API guarantees that for each request, either onCompleted or onErrorOccurred is fired as the final event with one exception: If a request is redirected to a data:// URL, onBeforeRedirect is the last reported event.

— Chrome, webRequest API

Each request has a requestId unique within a browser session for that extension; the ID stays constant for the whole life cycle, so you can correlate events. Several HTTP round-trips (redirects, authentication) can map to one logical web request.

webRequest addListener: filter, blocking, and BlockingResponse

Section titled “webRequest addListener: filter, blocking, and BlockingResponse”

Registration differs from ordinary events: callback, mandatory RequestFilter, and optional opt_extraInfoSpec.

To register an event listener for a web request, you use a variation on the usual addListener() function. In addition to specifying a callback function, you have to specify a filter argument, and you may specify an optional extra info argument.

— Chrome, webRequest API

RequestFilter limits events by URL patterns (for example *://www.google.com/foo*bar), ResourceType (main_frame, sub_frame, image, and others), tabId, and windowId. See RequestFilter.

With 'blocking' in opt_extraInfoSpec, the callback runs synchronously and the request waits until it returns. The return value can be a BlockingResponse: cancel, redirectUrl (on onBeforeRequest / onHeadersReceived), requestHeaders, responseHeaders, or authCredentials on onAuthRequired. 'asyncBlocking' is only for onAuthRequired.

webRequest limits: permissions, CORS, WebSocket, and WebTransport

Section titled “webRequest limits: permissions, CORS, WebSocket, and WebTransport”

The API only shows requests your extension has host permission to see. Supported schemes include http://, https://, ftp://, file://, ws://, wss://, urn:, and chrome-extension://, with some sensitive URLs hidden. From Chrome 72, intercepting a request requires host permissions for both the request URL and the initiator.

Header changes interact with CORS: from Chrome 79, cross-origin header edits can trigger preflights; 'extraHeaders' in opt_extraInfoSpec is required to see or modify sensitive headers (Origin, Cookie, Set-Cookie, and others) and has a performance cost—use only when necessary. Modifying Origin does not change the immutable request initiator from the Fetch spec, which can still cause CORS failures.

WebSocket handshake interception is supported; individual messages and close events are not. WebTransport over HTTP/3 handshake fits the HTTP-oriented model, but post-handshake session traffic is not observable via webRequest.

webNavigation API: page load state the user sees

Section titled “webNavigation API: page load state the user sees”

Use webNavigation when you care about navigation state aligned with the UI, not every subresource on the wire.

Use the chrome.webNavigation API to receive notifications about the status of navigation requests in-flight.

— Chrome, webNavigation API

All methods and events need the "webNavigation" permission in the manifest (permissions).

webNavigation event order vs SPA and back-forward cache

Section titled “webNavigation event order vs SPA and back-forward cache”

For a completed navigation:

onBeforeNavigate → onCommitted → [onDOMContentLoaded] → onCompleted

Errors end with onErrorOccurred and no further events for that navigation. Parent frames commit before child onBeforeNavigate; parent onCompleted fires after all children complete.

Separate events cover onHistoryStateUpdated (history.pushState()), onReferenceFragmentUpdated (hash changes), onTabReplaced (pre-rendered tab swap), and onCreatedNavigationTarget (new tab/window). Back-forward cache restores may skip onDOMContentLoaded because content was already loaded.

onCommitted carries transitionType and qualifiers such as client_redirect, server_redirect, forward_back, and from_address_bar (transition qualifiers).

webNavigation vs webRequest: no guaranteed ordering

Section titled “webNavigation vs webRequest: no guaranteed ordering”

There is no defined ordering between events of the webRequest API and the events of the webNavigation API. It is possible that webRequest events are still received for frames that already started a new navigation, or that a navigation only proceeds after the network resources are already fully loaded.

— Chrome, webNavigation API

In general, the webNavigation events are closely related to the navigation state that is displayed in the UI, while the webRequest events correspond to the state of the network stack which is generally opaque to the user.

— Chrome, webNavigation API

Goal Prefer
Block ads, rewrite headers on XHR/fetch webRequest or declarativeNetRequest
Know when the visible URL committed or DOM is ready webNavigation
Declarative block/redirect without blocking listeners declarativeNetRequest
DevTools panel tied to inspected page navigation devtools.network onNavigated

frameId and documentId: tie requests to frames and documents

Section titled “frameId and documentId: tie requests to frames and documents”

Both APIs identify where a request or navigation runs. Main frame uses frameId 0; subframes use positive IDs unique within a tab. For document loads (main_frame / sub_frame), frameId is the frame that loads the document, not an outer frame.

The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens.

— Chrome, declarativeNetRequest API

A frame can keep the same frameId across navigations while the document changes, so Chrome added documentId (UUID per document) and documentLifecycle on many events from Chrome 106 onward. Use documentId when you must know which document instance caused an event, not just which frame slot.

Multi-process navigation can produce overlapping event sequences with the same frameId until onCommitted; provisional cross-site redirects may repeat onBeforeNavigate / onErrorOccurred. Pre-rendered tabs may be inaccessible via tabs or getAllFrames() until onTabReplaced.

The debugger API adds another layer for debugging: frames do not map one-to-one to debug targets—same-process frames may share a target but use different execution contexts; out-of-process iframes may get separate targets (Work with frames).

declarativeNetRequest: static rules instead of blocking listeners

Section titled “declarativeNetRequest: static rules instead of blocking listeners”

declarativeNetRequest matches network events against declarative conditions and applies actions (block, redirect, modifyHeaders, and others) without a synchronous JavaScript handler per request— the modern replacement for patterns that used imperative webRequest blocking or legacy declarativeWebRequest RequestMatcher stages.

Rule conditions: urlFilter, domains, and initiator vs request URL

Section titled “Rule conditions: urlFilter, domains, and initiator vs request URL”

Rule conditions include:

  • urlFilter or regexFilter (only one; RE2 for regex; ASCII patterns against punycode/encoded URLs).
  • initiatorDomains / excludedInitiatorDomains—match the request initiator, not the request URL (replaces deprecated domains / excludedDomains).
  • requestDomains / excludedRequestDomains—match the request URL’s domain.
  • topDomains / excludedTopDomains—top-level frame domain (initiator used when no top-level frame, e.g. Service Worker).
  • resourceTypes, requestMethods, tabIds (session rules), responseHeaders / excludedResponseHeaders, and more.

urlFilter supports *, |, ||, and ^ separator semantics as documented on declarativeNetRequest. Redirect actions support url, extensionPath, regexSubstitution, or transform (URLTransform); redirects to JavaScript URLs are not allowed.

Matched rules report MatchedRule with tabId (or -1 if the tab is gone) and timeStamp in epoch milliseconds—same convention as webRequest timestamps.

Filtered events: UrlFilter on navigation listeners

Section titled “Filtered events: UrlFilter on navigation listeners”

Filtered events let listeners declare interest up front so the browser does not wake a service worker for irrelevant URLs.

Filtered events are a mechanism that allows listeners to specify a subset of events that they are interested in. A listener that uses a filter won’t be invoked for events that don’t pass the filter, which makes the listening code more declarative and efficient.

— Chrome, events API

webNavigation listeners accept { url: events.UrlFilter[] }. URL filters use UrlFilter criteria (hostSuffix, hostContains, pathPrefix, urlMatches with RE2, schemes, ports, cidrBlocks, and others). All criteria are case sensitive. URL matching matches declarative expressiveness except scheme and port on navigation event filters.

Example pattern from the docs: replace manual host checks on onCommitted with {url: [{hostSuffix: 'google.com'}, {hostSuffix: 'google.com.au'}]}.

API Role
devtools.network onNavigated when the inspected window navigates—DevTools extensions only
mimeHandler Intercept MIME types; embedded marks iframe/embed/object loads
runtime ContextFilter Match extension contexts; unspecified fields match all ({} matches everything)
webview request Guest-page webRequest with webview.request.onBeforeRequest; declarative rules via webViewRequest types

Legacy MV2 references (chrome.webRequest, chrome.webNavigation, chrome.declarativeNetRequest) describe the same lifecycles with chrome.* naming.

Common mistakes when wiring network and navigation

Section titled “Common mistakes when wiring network and navigation”
  • Assuming webNavigation onCompleted means every webRequest for that page has finished—they are not ordered relative to each other.
  • Correlating only frameId across navigations instead of documentId when the document instance matters.
  • Using initiatorDomains in declarative rules when you meant the request URL host (requestDomains).
  • Enabling blocking webRequest on broad filters—blocks the network thread; prefer declarativeNetRequest for static block lists.
  • Omitting extraHeaders and expecting to read or strip Cookie, Set-Cookie, or Origin.
  • Parsing onErrorOccurred error strings in webRequest—the docs state the string is not guaranteed stable across releases.
  • Comparing timeStamp to Date.now() in the extension—webNavigation timestamps are only guaranteed consistent between events, not with extension-process clocks.
  1. Load an unpacked extension with the permissions you document (webNavigation, host permissions, or declarativeNetRequest rules) and reproduce a navigation or request you care about.
  2. Log requestId, frameId, and documentId in webRequest and webNavigation handlers to confirm correlation matches webRequest and webNavigation behaviour.
  3. Use Chrome DevTools Network on the target page while your extension runs to compare visible requests with what your filters allow.
  4. For declarative rules, use the extension’s rule-testing or match feedback APIs described on declarativeNetRequest (e.g. hypothetical request fields such as url, initiator, topUrl, type).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page disagrees with current Chrome behaviour or the linked references, email yimasynthetic@gmail.com with the page URL and the exact sentence you think is wrong, and we will correct or clarify it.