Browser Extension Architecture: Content Scripts, Service Workers and Permissions
Saket Bhatnagar, Founder, SevyDevy, Last updated , 23 min read
Summary
- Browser extension architecture in Manifest V3, the current Chrome extension format, splits one extension into parts that cannot share variables. Content scripts run inside web pages, and a background service worker handles events.
- The popup is a small page that opens under the toolbar icon. The parts talk by message passing, which means sending small data messages and replying to them.
- A content script sees the page's HTML but not its JavaScript. It runs in an isolated world, a private JavaScript environment that shares only the DOM, the page's tree of HTML elements.
- Permissions decide what the extension may touch. Ask for the least: activeTab gives temporary access to the current tab after the user invokes the extension, for example with a click, and shows no install warning.
- Beginners can stop after the permissions section. Engineers then get our Chromium 153 test table of what each part can really reach, why the service worker forgets state, and the update traps that disable extensions.
What goes wrong when you build a browser extension like a web page?
You put code in the wrong place. Logic that needs the page runs where the page cannot be seen, state sits in a variable that disappears, and the manifest asks for far more access than needed.
Browser extension architecture is the set of rules that decides where each piece of extension code runs and what it can reach. In a normal web app, one page holds your code, your state and your screen. An extension spreads them over several separate places.
Picture a common setup. A small team builds a quote saver: select text on any page, click the toolbar icon, press Save, and the quote lands in a reading list. The setup is made up, but each failure below is documented Chrome behaviour. On a laptop with DevTools, Chrome's built-in developer tools, open, everything worked. After release, three problems arrived.
- A counter of saved quotes kept resetting to zero. It lived in a global variable inside the service worker, which Chrome stops when it is idle.
- The first manifest asked to read every website. Users saw a broad warning at install, and the store treats broad host access as a reason for closer review.
- A later update added access to one more site. Chrome disabled the extension for existing users until each one accepted the new warning.
None of these are Chrome bugs. They are the architecture working as designed. This guide follows the same quote saver from its manifest to the Chrome Web Store.
Which words do you need before reading about extensions?
You need six words. Each gets a plain meaning and a quote saver example.
- Manifest. The manifest.json file at the root of the extension. It lists the parts, the permissions and the version. Chrome reads it first.
- Manifest V3. Version 3 of the manifest format, often shortened to MV3. As of 30 October 2026, Chrome 139 and later no longer run the older Manifest V2 extensions.
- Content script. A JavaScript file the extension runs inside a web page. The quote saver uses one to read the text you selected.
- Service worker. The extension's background script. It wakes up for events, such as a message, and Chrome stops it when nothing is happening.
- Permission. A named power the extension asks for in the manifest, such as storage. A host permission is access to particular websites.
- Match pattern. A website address with wildcards, such as one pattern that covers every HTTPS site. Host permissions and content scripts use them.
What is browser extension architecture in Manifest V3?
Browser extension architecture in Manifest V3 has three kinds of running parts, tied together by the manifest. Content scripts touch web pages, the service worker coordinates, and extension pages such as the popup show your own screens.
Each part runs in its own JavaScript environment. A variable set in one part does not exist in another. They mainly share data in two ways: by sending messages, or by writing to the chrome.storage API, which every part can reach in some form.
Here is one everyday picture for the hardest idea. Think of a newspaper. The content script is a reporter at the scene. It can see everything there, but it cannot print the paper. The service worker is the news desk. It holds the tools, such as Chrome APIs for tabs and storage, but it never sees the scene. The popup is the front counter, open only while a visitor stands at it.
Where the picture breaks: a real news desk does not fall asleep. The service worker is stopped after about 30 seconds without events, and it forgets anything not written down in storage. A later section shows this on a real run.
The parts of a Manifest V3 extension
Drag to exploreNotice there is no arrow between the page's scripts and the content script. They meet only through the shared DOM. The powerful Chrome APIs sit with the service worker and extension pages, not the content script.
Diagram connections:
- Page scripts to Shared DOM (reads and edits)
- Content script to Shared DOM (reads and edits)
- Content script to Service worker (runtime.sendMessage)
- Popup page to Service worker (runtime.sendMessage)
- Service worker to Chrome APIs (calls, if permitted)
- Popup page to Chrome APIs (calls, if permitted)
- Service worker to chrome.storage (saves state)
- Page scripts: The site's own JavaScript, in the main world
- Shared DOM: The HTML both sides can read and change
- Content script: Isolated world, only a few Chrome APIs
- Service worker: Handles events, most Chrome APIs, no DOM
- Popup page: Opens on toolbar click, unloads on close
- Chrome APIs: tabs, scripting, alarms, gated by permissions
- chrome.storage: local and session areas for saved state
| Part | Where it runs | Can touch the page's HTML? | Chrome APIs it can call | How long it lives |
|---|---|---|---|---|
| Content script | Inside each matching web page, in an isolated world | Yes, it shares the DOM | Per Chrome's docs, only dom, i18n, storage and part of runtime | As long as the page stays open |
| Service worker | In the background, one per extension | No, it has no document at all | Every API the manifest grants | Stopped after about 30 seconds idle, woken by events |
| Popup and other extension pages | In their own extension page | No, only its own page | Every API the manifest grants | Closes when the user clicks away, and starts fresh on the next open |
The popup row has a trap of its own. Chrome's popup guide says a popup closes as soon as the user clicks elsewhere. MDN's cross-browser extension docs add that its document is unloaded on close and loaded again on open. So a variable in the popup also starts fresh on every click.
Why can't my content script see the page's JavaScript variables?
Because it runs in an isolated world. Chrome's docs call this a private execution environment that the page and other extensions cannot reach. The content script and the page share the DOM, but not variables, functions or built-in objects.
This protects both sides. A page cannot read your extension's variables, and a page that breaks its own built-ins cannot break yours. We checked both directions on Chromium 153. Our test page set a variable and replaced JSON.stringify with a function returning a fake string.
- The content script saw the page variable as undefined, but it read a data attribute the page had set on the body element.
- The content script's own JSON.stringify still returned the correct text. The page's copy returned the fake string.
- The page saw the content script's variable as undefined.
The quote saver relies on this. Its injected script reads the selected text through the DOM, which works because the selection belongs to the shared page. It never needs the page's variables.
When the main world is the right choice
You can ask Chrome to run a script in the main world instead, through the world option. That world is shared with the page's JavaScript, so the script can see page variables. The page can also see and tamper with it, and the page's Content Security Policy, its list of allowed script sources, applies.
Use the main world only when you must call the page's own functions. Keep anything that reaches Chrome APIs in the isolated world.
How do the parts of an extension send messages to each other?
They use one-time messages or long-lived connections. A content script or popup calls chrome.runtime.sendMessage, and the service worker answers in a chrome.runtime.onMessage listener. To reach a content script, the extension calls chrome.tabs.sendMessage with the tab's ID.
For a conversation with many messages, chrome.runtime.connect opens a port, a channel both ends keep open. Messages from other extensions and web pages arrive on separate events, onMessageExternal and onConnectExternal. Web pages can only use them if the manifest lists them under externally_connectable.
The diagram follows one Save in the quote saver. Read each box's note as who sends what to whom.
One Save in the quote saver
Drag to exploreLook at the decision box. The service worker checks every message before writing to storage, because the content script runs next to an untrusted page.
Diagram connections:
- User clicks the icon to activeTab grant (user gesture)
- activeTab grant to executeScript (Save pressed)
- executeScript to Read the selection
- Read the selection to save-quote message (runtime.sendMessage)
- save-quote message to Valid message?
- Valid message? to storage.local (Yes)
- Valid message? to Reply to sender (No: ok false)
- storage.local to Reply to sender (then ok true)
- User clicks the icon: User → toolbar: popup opens
- activeTab grant: Chrome → extension: access to this tab only
- executeScript: Popup → tab: run a small function
- Read the selection: Injected script → page DOM
- save-quote message: Injected script → service worker
- Valid message?: Service worker → itself: type and text checked
- storage.local: Service worker → storage: quote appended
- Reply to sender: Service worker → injected script
Here is the quote saver's service worker listener. We ran it unchanged on Chromium 153.
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg?.type !== 'save-quote') return;
const text = String(msg.text || '').slice(0, 500);
if (!text) {
sendResponse({ ok: false, reason: 'empty' });
return;
}
chrome.storage.local.get({ quotes: [] })
.then(function (data) {
data.quotes.push({ text: text, url: sender.tab?.url ?? '', savedAt: Date.now() });
return chrome.storage.local.set({ quotes: data.quotes });
})
.then(function () {
sendResponse({ ok: true });
});
return true; // keep the reply channel open for the async work
});What just happened? The listener ignores any message that is not a save-quote, so the sender gets no reply. It turns the text into a string and cuts it to 500 characters before storing. In our run, a 600-character quote was saved as 500 characters, and an empty one got ok false.
The last line matters most. Saving is asynchronous, which means the reply comes after the listener has already returned. Returning the literal value true tells Chrome to keep the reply channel open. We also returned the string yes instead, and the sender received undefined, as the docs warn.
Chrome's messaging docs say a listener may return a promise from Chrome 148, with the rollout happening gradually. It worked in our Chromium 153 run. The docs also say promise replies stay off in extensions that add a DevTools page. As of 30 October 2026, return true remains the choice that works everywhere.
Chrome's docs call content scripts less trustworthy than the service worker. Validate their messages, limit what they can trigger, and never pass message data to eval, which runs a string as code, or innerHTML, which parses a string as HTML. Also assume anything you send to a content script may leak to the page.
How do extension permissions work?
Extension permissions are declared in the manifest and accepted by the user. Some show a warning at install, some are granted only when the user asks, and activeTab grants access to one tab for a short time.
| Manifest field | What goes in it | When the user decides | Quote saver uses it? |
|---|---|---|---|
| permissions | Named APIs such as storage, scripting, tabs or activeTab | At install; some names show a warning | Yes: activeTab, scripting, storage |
| host_permissions | Match patterns for sites the extension may read and change | At install; adding patterns shows a warning | No |
| optional_permissions | Named APIs to ask for later | At runtime, after a click in your page | No |
| optional_host_permissions | Match patterns to ask for later | At runtime, after a click in your page | Yes: for a future auto-save feature |
| content_scripts matches | Sites where a content script runs on its own | At install; adding patterns shows a warning | No |
Here is the quote saver's whole manifest. It loaded without errors on Chromium 153.
{
"manifest_version": 3,
"name": "Quote saver",
"version": "1.0.0",
"action": { "default_popup": "popup.html" },
"background": { "service_worker": "background.js" },
"permissions": ["activeTab", "scripting", "storage"],
"optional_host_permissions": ["https://*/*"]
}There is no host_permissions field and no automatic content script. The quote saver only runs a script when the user clicks, using activeTab and the scripting permission together.
What activeTab grants, and when
activeTab gives temporary access to the tab the user is on when they invoke the extension. Chrome's docs list four ways to invoke it. The user clicks the action, chooses a context menu item or presses a keyboard shortcut from the commands API. The fourth is accepting an address bar suggestion from the omnibox API.
The grant stays while the user remains on that site. It ends when the tab closes or moves to a different site. It shows no install warning, and it never works on restricted pages such as chrome:// pages.
You can see the difference yourself. Before any click, our test called chrome.scripting.executeScript on an open tab and got this error: Cannot access contents of the page. Extension manifest must request permission to access the respective host. The same test showed tabs with no url field, because the extension had no tabs or host permission.
Then we simulated a toolbar click with Extensions.triggerAction, a command in the Chrome DevTools Protocol, the remote-control interface test tools use. Chrome's activeTab page does not mention popups. In our run, the quote saver has a popup, and the simulated click still granted access. This is undocumented as of 30 October 2026; pin your version.
After the simulated click, executeScript worked on that one tab and failed on the other. It kept working after a move to another path on the same site. After the tab moved to a different host, it failed again.
Optional permissions need a user gesture
Optional permissions are asked for at runtime with chrome.permissions.request. Chrome only allows that call during a user gesture, such as a button click. We called it from a timer instead, and Chrome rejected it with: This function must be called during a user gesture.
A few permissions can never be optional. Chrome's permissions reference lists debugger, declarativeNetRequest, devtools, geolocation, mdns, proxy, tts, ttsEngine and wallpaper.
To see the warnings users will see, Chrome's docs suggest packing the extension from chrome://extensions in developer mode. Drop the resulting .crx file, the packed extension, onto the same page to view the install prompt.
For engineers
Beginners can stop here. You now know the parts, how they talk and how permissions work. The sections below are for engineers shipping to real users: the worker lifecycle, our test results, the remote code ban and update traps.
Why does the extension service worker forget its state?
Because Chrome stops it when it is idle, and global variables die with it. Chrome's lifecycle docs give three limits: 30 seconds without activity, five minutes for a single event or API call, and 30 seconds waiting for a fetch response.
Receiving an event resets the idle timer, and from Chrome 110 so does calling an extension API. A new event wakes a stopped worker. The worker then starts from the top of its script, with every global variable back at its first value.
What our restart test showed
Our test worker kept a counter in two places: a global variable and chrome.storage.session. We sent two messages, then stopped the worker with ServiceWorker.stopAllWorkers, another Chrome DevTools Protocol command.
- Before the stop, both counters read 1 and then 2.
- After the stop, the next message woke a new worker with a new start time.
- The global counter read 1 again. The session storage counter read 3.
This is the quote saver's first bug. The fix is to keep every value that must outlive one event in chrome.storage.
| Place | Survives a worker stop? | Cleared when | Content scripts can read it? |
|---|---|---|---|
| Global variable in the service worker | No | Every time the worker stops | No |
| chrome.storage.session | Yes | Extension disabled, reloaded or updated, or browser restart | Not by default |
| chrome.storage.local | Yes | The extension is removed | Yes, by default |
Chrome's storage docs give both areas a 10 MB quota as of 30 October 2026. The unlimitedStorage permission lifts the limit for the local area. Service workers cannot use localStorage at all; in our run it was undefined.
Three habits that survive restarts
- Register every event listener at the top level of the script, synchronously. Chrome's docs show that a listener added inside a callback is not advised.
- Use chrome.alarms, Chrome's timer API that can wake the worker, instead of setTimeout for anything that must happen later. From Chrome 120, alarms can run as often as every 30 seconds.
- When you need the DOM, for example to parse HTML, use an offscreen document. It is a hidden extension page, and normally only one can be open at a time.
What can each extension part reach in our Chromium 153 tests?
We loaded a test extension into Chromium 153 (Chrome for Testing 153.0.8010.12) with Playwright 1.63. Each row below is one check, with the result we got. The test scripts and outputs are kept with this guide's claim ledger.
| Check | Result |
|---|---|
| Content script reads a page variable | undefined |
| Content script reads chrome.tabs | undefined; the extension namespaces present were dom, extension, i18n, runtime, scripting (constants only) and storage |
| Content script reads storage.session | Error: Access to storage is not allowed from this context. |
| Service worker reads document, window and localStorage | All three undefined |
| eval or new Function in the service worker or popup | EvalError from the Content Security Policy |
| Popup loads a script from a remote https address | Blocked by the Content Security Policy |
| Manifest adds unsafe-eval to the extension pages policy | Extension fails to load: Insecure CSP value |
| Listener returns a truthy string, replies later | Sender receives undefined |
| executeScript on a site not granted | Error: Cannot access contents of the page |
| executeScript after a simulated toolbar click (activeTab) | Works on that tab only; fails again after the tab moves to another host |
Two rows surprise people. A content script holds a chrome.scripting object, but it carries only a few properties such as the ExecutionWorld constants, not executeScript. This is undocumented as of 30 October 2026; pin your version. And the eval error appears even for a constant string, not only for code fetched from the network.
What does the Chrome Web Store ban on remote code forbid?
It forbids running JavaScript that is not inside your submitted package. Chrome's Manifest V3 requirements say reviewers must be able to see the extension's full behaviour from the code you submit.
- Not allowed: a script element that loads a file from outside the package.
- Not allowed: fetching a string from a server and running it with eval or anything similar.
- Not allowed: building an interpreter that runs complex commands fetched as data.
- Allowed: fetching data such as settings, feature flags or images, when all the logic that uses them ships in the package.
- Allowed: remote code through the two documented exceptions, the debugger API and the User Scripts API, only for their stated purpose.
The browser enforces part of this for you. The default Content Security Policy for extension pages allows scripts only from the extension itself. You may add wasm-unsafe-eval for WebAssembly, but not unsafe-eval; our test extension with unsafe-eval did not load at all.
Sandboxed pages are the escape hatch for libraries that need eval. Code in them is exempt from the remote loading rule, but the store still expects its behaviour to be clear from your package.
Which update and review mistakes break a published extension?
The biggest one is adding a permission that shows a new warning. Chrome's docs say the extension is disabled until the user accepts the new permission. Until then, it does nothing for that user.
Diff permissions before every release
Compare permissions, host_permissions and content_scripts matches with the last published version. Any added warning will disable the extension for current users.
Move new access to optional permissions
Ask for new sites with chrome.permissions.request after a click. Existing users keep working, and only those who want the feature see a prompt.
Expect review time
Chrome's review page, last updated in December 2021, says most reviews finish within a few days but can take up to a few weeks. Updates go through the same review.
Avoid review triggers you do not need
The same page says broad host access, sensitive execution permissions, significant code changes and large codebases can lengthen review. Minified code is allowed; obfuscated code is not.
Test the update path
Remember that an update clears chrome.storage.session. Reload the unpacked extension and check that the worker rebuilds what it needs from chrome.storage.local.
The program policies add one rule that decides many rejections. Request the narrowest permissions your features need, and do not request permissions for features you have not built yet.
Manifest V2, the older format with long-running background pages, has been switched off. Chrome's timeline says Chrome 138 disabled Manifest V2 extensions for all users, and from Chrome 139 they stop working. Its entry of 31 August 2026 says the remaining ones were removed from the store.
In the interview
How do you explain browser extension architecture in a system design interview?
Explain it as a set of separate contexts with a trust boundary, then walk one user action through them.
Name the parts
Content scripts in pages, one service worker for events and privileged APIs, and extension pages such as the popup.
Draw the trust boundary
The page is untrusted. The content script sits next to it in an isolated world and has few powers. The service worker validates every request.
Walk one action
For the quote saver: click, activeTab grant, executeScript, read the selection, send a message, validate, save to chrome.storage.local, reply.
Handle the lifecycle
Say that the worker stops after about 30 seconds idle. Keep state in storage, register listeners at the top level and use alarms.
Defend the permissions
Justify each permission. Prefer activeTab and optional host permissions so updates never add an install warning.
Interviewers like a number. You can say the worker idles out after about 30 seconds, and that storage.session and storage.local each hold 10 MB as of 30 October 2026.
Questions people ask
What is the difference between a content script and a service worker in an extension?
A content script runs inside a web page, while the service worker runs in the background for the whole extension. The content script can read and change the page's HTML but can call only a few Chrome APIs. The service worker can call every API the manifest grants but has no page and no DOM. They talk by sending messages.
Can a content script access the page's JavaScript variables?
No, not from the default isolated world. The content script and the page share the DOM but keep separate JavaScript environments, so page variables read as undefined. If you truly need page variables, you can inject a script into the main world, but the page can then see and tamper with that script too.
Why does my extension service worker lose its global variables?
Because Chrome stops the worker when it is idle and starts it fresh on the next event. Chrome's docs give about 30 seconds without events as the idle limit. Store anything that must last in chrome.storage.session or chrome.storage.local, and register listeners at the top level of the script.
Does activeTab show a permission warning at install?
No, activeTab shows no install warning. It gives temporary access to the current tab only after the user invokes the extension, for example by clicking its toolbar icon. Access ends when the user closes the tab or moves to a different site, and it never covers chrome:// pages.
Can a Manifest V3 extension load code from a server?
No, it cannot load and run JavaScript from outside its package. The Chrome Web Store bans remotely hosted code, and the extension Content Security Policy blocks remote scripts and eval in extension pages. Extensions may still fetch data, such as settings or images, if all the logic that uses that data ships in the package.
Why was my extension disabled after an update?
Most likely the update added a permission with a new warning. Chrome disables the extension until the user accepts the new permission. Compare permissions, host_permissions and content script matches before each release, and move new access into optional permissions that users grant later with a click.
Keep learning
Practise it with Lala
A question on this guide, hints and a review.
Read next
Sources (22)
- Chrome for Developers: Content scripts (isolated worlds, available APIs, injection, run_at)
- Chrome for Developers: The extension service worker lifecycle
- Chrome for Developers: Extension service worker events (top-level listeners)
- Chrome for Developers: Message passing
- Chrome for Developers: Declare permissions
- Chrome for Developers: The activeTab permission
- Chrome for Developers: Permission warning guidelines
- Chrome for Developers: chrome.permissions API reference
- Chrome for Developers: chrome.scripting API reference (ExecutionWorld)
- Chrome for Developers: chrome.storage API reference
- Chrome for Developers: chrome.offscreen API reference
- Chrome for Developers: chrome.action API reference (popup)
- Chrome for Developers: Add a popup (popups close when focus leaves)
- Chrome for Developers: Manifest content_security_policy
- Chrome for Developers: Debug extensions tutorial (inspecting keeps the worker active)
- Chrome for Developers: Test service worker termination with Puppeteer
- Chrome for Developers: Manifest V2 support timeline
- Chrome Web Store program policies: Manifest V3 requirements (remotely hosted code)
- Chrome Web Store program policies: Use of permissions
- Chrome Web Store: Chrome Web Store review process
- MDN Web Docs: Content scripts (WebExtensions)
- MDN Web Docs: Popups (WebExtensions user interface)