The Core Architectural Shift in Manifest V3
Manifest V3 fundamentally changes how browser extensions execute background logic, handle network requests, and persist data. Google introduced these changes starting with Chrome 88 to improve security, privacy, and performance by eliminating persistent background pages and blocking webRequest listeners that could inspect or modify every request synchronously.
Instead of a long-lived background page that stays in memory, developers must use a service worker declared in the manifest.json under the background.service_worker key. This worker runs only when events fire and can be terminated by the browser when idle. The Declarative Net Request (DNR) API replaces the blocking version of chrome.webRequest, requiring rules to be declared statically or updated dynamically within limits. Storage options remain through chrome.storage but come with new considerations around quotas and synchronous access patterns.
These changes force explicit patterns around state persistence, lazy initialization, and rule management that were unnecessary in Manifest V2. Production extensions such as password managers, privacy tools, and productivity enhancers have all adapted these patterns successfully. The trade-off is increased complexity in exchange for stronger isolation and reduced attack surface.
Structuring the Manifest V3 File
A minimal production manifest.json for a Manifest V3 extension looks like this:
{
"manifest_version": 3,
"name": "Example Privacy Extension",
"version": "1.2.3",
"background": {
"service_worker": "background.js",
"type": "module"
},
"permissions": ["storage", "declarativeNetRequest"],
"host_permissions": ["https://*.example.com/*"],
"action": {
"default_popup": "popup.html"
},
"content_scripts": [{
"matches": ["https://*.example.com/*"],
"js": ["content.js"]
}]
}
Note the explicit host_permissions instead of broad "<all_urls>" where possible. Using type: "module" allows ES modules in the service worker, enabling clean imports. Versioning follows semantic rules because Chrome Web Store updates are reviewed more strictly for Manifest V3.
Firefox 109+ and Edge 112+ support the same structure with minor differences in permission granting. Always test with webextension-polyfill version 0.10.0 or newer for cross-browser compatibility.
Service Worker Lifecycle Management
Service workers in Manifest V3 follow the standard web service worker lifecycle but with Chrome-specific behaviors. The worker starts on events such as onInstalled, onStartup, onMessage, or DNR rule evaluation. Chrome can terminate the worker after approximately 30 seconds of inactivity in many cases, though this is not a hard guarantee and varies by device resources.
To handle this, persist all critical state immediately using chrome.storage.local or chrome.storage.session (new in Manifest V3 for in-memory but extension-scoped data). Avoid relying on global variables for anything that must survive termination.
Key event listeners to register immediately in background.js:
chrome.runtime.onInstalled.addListenerfor migration and initial rule installationchrome.runtime.onStartup.addListenerfor restoring state on browser startchrome.alarms.onAlarm.addListenerfor scheduled work without persistent timerschrome.runtime.onMessage.addListenerfor communication from popups and content scripts
Register alarms with chrome.alarms.create('daily-sync', { periodInMinutes: 60 * 24 }). Alarms survive worker termination and wake the service worker when they fire. This pattern is used by popular extensions to refresh filter lists daily without keeping the worker constantly alive.
Trade-off: Cold starts add 10-50ms latency to the first action after termination. Measure this using chrome.runtime.getContexts or performance marks in production telemetry.
Practical Service Worker Patterns
Here is a production-grade skeleton for background.js using ES modules:
import { installRules } from './rules.js';
import { migrateStorage } from './storage.js';
let isInitialized = false;
async function initialize() {
if (isInitialized) return;
await migrateStorage();
await installRules();
isInitialized = true;
}
chrome.runtime.onInstalled.addListener(async (details) => {
if (details.reason === 'install' || details.reason === 'update') {
await initialize();
}
});
chrome.runtime.onStartup.addListener(initialize);
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'GET_STATUS') {
initialize().then(() => {
sendResponse({ status: 'ready', rulesActive: true });
});
return true; // async response
}
});
// Dynamic rule updates limited to 1000 rules per session
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((info) => {
console.debug('Rule matched:', info);
});
This pattern ensures initialization happens exactly once per worker lifetime. The return true in the message listener is required for asynchronous sendResponse. Use ES modules to split large rule sets or storage logic into separate files, keeping the main worker under 500KB to reduce cold-start time.
Declarative Net Request Rules in Depth
The declarativeNetRequest API requires rules to be defined in JSON format with conditions and actions. Rules can be static (bundled in the manifest under declarative_net_request) or dynamic (added at runtime with chrome.declarativeNetRequest.updateDynamicRules).
Static rules live in files referenced like this in manifest.json:
"declarative_net_request": {
"rule_resources": [{
"id": "blocklist",
"enabled": true,
"path": "rules/blocklist.json"
}]
}
A concrete blocklist rule example (rules/blocklist.json):
[
{
"id": 1,
"priority": 1,
"action": { "type": "block" },
"condition": {
"urlFilter": "||analytics.example.com",
"resourceTypes": ["xmlhttprequest", "script", "image"]
}
},
{
"id": 2,
"priority": 2,
"action": {
"type": "redirect",
"redirect": { "url": "https://privacy.example.com/blank.gif" }
},
"condition": {
"urlFilter": "||tracking.example.com/pixel",
"resourceTypes": ["image"]
}
}
]
Priority values matter: higher numbers win when multiple rules match. The maximum number of dynamic rules per extension is 5000 in Chrome 120+, but static rules have higher limits (up to 30,000). Test rule collisions using the chrome.declarativeNetRequest.testMatchOutcome API introduced in Chrome 103.
Modify headers safely with "type": "modifyHeaders" actions. Example for removing tracking cookies:
{
"id": 10,
"priority": 1,
"action": {
"type": "modifyHeaders",
"responseHeaders": [{
"header": "set-cookie",
"operation": "remove"
}]
},
"condition": {
"urlFilter": "||thirdparty.com",
"resourceTypes": ["xmlhttprequest"]
}
}
Trade-off: Unlike the old webRequest API, you cannot run arbitrary JavaScript on each request. All logic must be expressed declaratively, pushing complex decisions into rule generation code that runs only when lists update.
Worked Example: Privacy Filter Extension
Consider a realistic privacy filter that blocks known tracking domains, lets users add custom rules via a popup, and persists those rules across browser restarts.
Full manifest snippet for this example:
{
"manifest_version": 3,
"permissions": ["declarativeNetRequest", "storage", "declarativeNetRequestFeedback"],
"host_permissions": ["<all_urls>"],
"declarative_net_request": {
"rule_resources": [{
"id": "default",
"enabled": true,
"path": "rules/default.json"
}]
}
}
In rules.js, provide functions to generate user rules with incremental IDs starting from 10000 to avoid clashing with static rules (which should use IDs under 1000):
export async function addUserRule(domain) {
const newRule = {
id: Date.now() % 1000000 + 10000,
priority: 10,
action: { type: "block" },
condition: {
urlFilter: `||${domain}`,
resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest", "script"]
}
};
await chrome.declarativeNetRequest.updateDynamicRules({
addRules: [newRule],
removeRuleIds: []
});
const currentRules = await chrome.storage.local.get('userRules');
const updated = [...(currentRules.userRules || []), newRule];
await chrome.storage.local.set({ userRules: updated });
}
The popup can call this via messaging:
const response = await chrome.runtime.sendMessage({
type: 'ADD_RULE',
domain: 'badtracker.com'
});
This pattern separates rule generation, storage, and application layers, making testing easier. Measure rule evaluation performance: Chrome's DNR engine typically evaluates 10,000 rules in under 1ms on modern hardware.
chrome.storage Patterns and Quotas
chrome.storage.local is the primary choice for larger datasets. As of Chrome 120, the practical limit is roughly 5MB per extension for synced devices, though local storage can exceed 100MB on desktop. Use chrome.storage.session for data that should clear on browser restart (introduced specifically for Manifest V3 service workers).
Best practice is to store only necessary data and compress large filter lists using Uint8Array with gzip compression before storage. Example storage wrapper:
class StorageManager {
async get(key) {
const result = await chrome.storage.local.get(key);
return result[key];
}
async set(key, value) {
// Automatic migration and quota warning
const bytesInUse = await chrome.storage.local.getBytesInUse(key);
if (bytesInUse > 4000000) {
console.warn('Approaching storage quota');
}
await chrome.storage.local.set({ [key]: value });
}
}
export const storage = new StorageManager();
For sync storage, respect the hard limit of 102,400 bytes total and 8,192 bytes per item. Many extensions use local storage for filter lists and only sync user preferences.
Listen for changes with chrome.storage.onChanged.addListener to react to updates from the popup without polling. This pattern keeps the service worker responsive to user configuration changes.
Message Passing and Long-Lived Connections
Because service workers can terminate, long-lived connections require careful management. Use chrome.runtime.connect to create ports that automatically reconnect on disconnect:
let port;
function connect() {
port = chrome.runtime.connect({ name: 'persistent-port' });
port.onDisconnect.addListener(() => {
setTimeout(connect, 1000); // reconnect after termination
});
}
connect();
For content script to background communication, inject the content script with run_at: "document_start" and use immediate port creation. Avoid sending large objects (over 1MB) as the structured clone algorithm has measurable cost.
Production pattern used by enterprise extensions: implement a request-response pattern with unique message IDs and Promise wrappers. This abstracts the async nature of service worker wake-up.
Permissions Strategy and Least Privilege
Request only the permissions actually needed. Use optional permissions for advanced features. For DNR, the declarativeNetRequestWithHostAccess permission combined with specific host_permissions is preferred over the broader declarativeNetRequest when targeting Chrome 96+.
Content security policy in Manifest V3 is enforced more strictly. The default CSP prevents inline scripts and eval. If using WebAssembly (common for fast regex matching in filters), declare it explicitly:
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self';"
}
Extensions using WASM for matching see 3-5x performance improvements on large rule sets compared to pure JavaScript RegExp.
Performance Optimizations and Measured Trade-offs
Bundle size directly affects cold start time. Use esbuild 0.19+ or Rollup with terser to keep the service worker under 200KB uncompressed. Measure startup with the Chrome extension profiler or chrome.management.getSelf combined with performance.now() marks.
Rule updates should be batched. Updating 500 rules individually is significantly slower than a single updateDynamicRules call with all changes. Real-world extensions update filter lists every 4-6 hours using alarms and fetch with chrome.identity or simple fetch.
Memory usage: each active DNR rule consumes approximately 200 bytes. 10,000 rules add roughly 2MB to the extension process. This is acceptable for most use cases but becomes a consideration for enterprise policy extensions.
Compared to Manifest V2, cold-start latency increases by 15-40ms on average according to public Chrome team measurements. The security gain—removing the ability for extensions to run arbitrary code on every page load via blocking webRequest—outweighs this for most users.
Cross-Browser Compatibility Layer
Firefox implements DNR with slightly different limits (fewer maximum rules) and does not support all chrome.declarativeNetRequest feedback APIs. Use the webextension-polyfill library version 0.10.0 and feature-detect:
if (typeof browser !== 'undefined') {
// Firefox path - use browser.declarativeNetRequest
}
Edge follows Chrome closely but has different Web Store publishing requirements. Test on all three using the respective developer tools. For storage, Firefox has higher practical limits on browser.storage.local.
Testing, Debugging and Observability
Use chrome.declarativeNetRequest.getMatchedRules to verify which rules fired for a given navigation. The declarativeNetRequestFeedback permission allows users to report false positives directly to your extension.
Unit test rule generation logic with Jest 29+ by importing the rule builder functions outside the browser. For end-to-end testing, Puppeteer 21+ with extension loading support or Chrome's extension test harness.
Implement internal telemetry by sending anonymized rule match counts to your own backend (with user consent) using the fetch API from the service worker. This data helps prioritize rule list maintenance.
Publishing and Update Considerations
Manifest V3 extensions undergo stricter review in the Chrome Web Store, particularly around DNR rule lists that resemble ad blocking. Provide clear descriptions of all host permissions. Use the update_url field for self-hosted updates if not using the Web Store.
When updating rules frequently, version the rule files and use the chrome.runtime.reload() sparingly—only after critical security updates. Users see fewer permission prompts on updates if new permissions are added incrementally.
Current adoption (as of late 2024) shows over 85% of top 1000 Chrome extensions have successfully migrated to Manifest V3 using these exact patterns. Popular libraries like uBlock Origin Lite demonstrate that complex filtering remains possible within the declarative constraints through carefully engineered static and dynamic rule sets.
The combination of service worker discipline, declarative rules, and explicit storage patterns results in extensions that are more secure, use fewer resources when idle, and provide predictable performance for end users. Implementing these patterns from the start avoids painful refactoring later when scaling to handle thousands of daily active users.
