Blog / Build with AI /

Content scripts vs background scripts, in plain words

If you’ve started building a Chrome extension, you’ve hit the same wall as everyone: some code runs on web pages, some runs somewhere else, and nobody tells you why. Your code works in one place and throws errors in the other.

The two parts are content scripts and the background service worker. Once you see what each is for, a lot of extension errors stop being mysterious.

The one-minute version

  • A content script runs inside a web page. It can read and change that page.
  • The background service worker runs behind the scenes, outside any page. It can use Chrome’s browser features, but it can’t touch the page directly.
  • They pass messages to each other.

That’s it. The rest is detail.

An analogy

Picture a shop. The content script is the shop assistant on the floor. They see the customers and the shelves, and can move things around. But they can’t open the safe or call head office.

The background service worker is head office. It can make decisions, use the phone and handle the accounts, but it can’t see what’s happening on the shop floor.

When the assistant needs something done, they message head office. When head office needs something moved, it messages the assistant. Neither can do the other’s job.

Content scripts, in detail

What they can do

  • Read the page’s HTML and change it: highlight words, hide elements, add buttons, inject styles.
  • Listen to what happens on the page, such as clicks.
  • Use a few extension features, like chrome.runtime for messaging and chrome.storage.

What they can’t do

  • Use most Chrome extension APIs (tabs, alarms, bookmarks, and so on).
  • Share variables with the page’s own JavaScript. Content scripts run in an “isolated world”. They see the same page structure, but their JavaScript variables are separate from the page’s. That’s a safety feature, and it surprises people.
  • Make some cross-site requests freely. Content scripts are bound by the page’s rules on what they can fetch, so requests often go through the background worker instead.

How you declare one

In manifest.json:

"content_scripts": [
  {
    "matches": ["https://*/*"],
    "js": ["content.js"]
  }
]

The matches list decides which sites the script runs on. Keep it as narrow as you can. I explain why in extension permissions: asking for as little as possible.

The background service worker, in detail

What it can do

  • Use nearly all Chrome extension APIs: tabs, alarms, context menus, notifications, storage and more.
  • React to browser events: the extension being installed, a tab changing, a keyboard shortcut.
  • Make network requests for the extension.
  • Coordinate several tabs or pages.

What it can’t do

  • Touch the page. There’s no document and no window in a service worker. If you write document.querySelector there, you’ll get an error.
  • Stay alive. In Manifest V3 it starts when needed and stops when idle. Anything you store in a normal variable can disappear. Keep important data in chrome.storage, and set up your listeners at the top level of the file.

How you declare one

"background": {
  "service_worker": "background.js"
}

If the concept is new, Manifest V3 explained for extension builders gives the wider picture.

How they talk: messages

When the content script needs something from the background, it sends a message:

// content.js
chrome.runtime.sendMessage({ type: 'GET_COLOUR' }, (response) => {
  document.body.style.background = response.colour;
});

And the background listens and answers:

// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'GET_COLOUR') {
    sendResponse({ colour: '#ffe066' });
  }
});

The other direction works too, using chrome.tabs.sendMessage(tabId, ...) from the background to a specific tab’s content script.

Two things to remember:

  • Give messages a type so you can handle several kinds without confusion.
  • If you reply asynchronously, return true from the listener to keep the channel open. Forgetting this is a classic bug, where the response never arrives.

Which one should the code go in?

A handy rule: if it touches the page, it’s a content script. If it touches the browser, it’s the background.

Job Where
Highlight text on a page Content script
Add a button into a page Content script
Read what the user selected Content script
Save settings Either (with storage permission)
Open a new tab Background
Run on a timer (alarms) Background
Add a right-click menu item Background
Fetch data from your own server Background, usually
Listen for a keyboard shortcut Background

A tab manager, for example, lives mostly in the background and the popup, because it’s about tabs and not page contents. A highlighter lives mostly in content scripts, because it’s about the page. That split follows the job, not any preference.

Common myths

  • “A content script can use every Chrome API.” It can’t. Use the background for anything it can’t do.
  • “The background script runs all the time.” In Manifest V3 it doesn’t. Treat it as something that wakes up, does a job and sleeps.
  • “My page’s JavaScript can see my content script’s variables.” It can’t, by design.

Common mistakes, and how to debug them

  • Using document in the background. Move that code to a content script.
  • Using chrome.tabs in a content script. It’s undefined there. Ask the background.
  • Content script doesn’t run. Check the matches pattern, and remember it only loads on pages loaded after the extension, so reload the tab.
  • No response to a message. You may need return true in the listener, or the receiving end isn’t listening yet.

I’ll go into tools for tracking these down in a later post. For now, building a Chrome extension: the parts nobody explains covers other things that trip beginners up.

A prompt that helps when you’re building with AI

I’m building a Manifest V3 Chrome extension. Here’s what I want it to do: [describe]. Tell me which parts belong in the content script and which in the background service worker, and show the message passing between them.

Asking for the split first saves you from code that looks fine but runs in the wrong place.

Key takeaways

  • Content scripts live in the page; the service worker lives in the browser.
  • Content scripts change pages; the worker uses Chrome’s APIs.
  • They communicate with messages.
  • The worker sleeps, so keep state in storage.

Take an extension idea you have and list its jobs. Which ones touch the page, and which touch the browser?