Extension foundations

Understand extension contexts

Assign user interface, page access, browser events, and privileged API calls to popup, content script, and service worker contexts.

An extension is not one program. It’s several separate JavaScript environments, and each one sees a different slice of the browser. Chrome calls them contexts.

Page Notes uses three of them.

The popup

The popup is the small page that opens when you click the toolbar icon. It’s a normal HTML document with access to extension APIs. It exists only while it’s open. Click anywhere else and it’s gone, together with every variable in it.

The popup owns the user interface. Forms, buttons, status text. Nothing long-running belongs here.

The content script

A content script is JavaScript that Chrome runs inside a web page. It sees the page’s DOM and can change it. It’s the only context in Page Notes that can touch the host page.

It runs in an isolated world. That means it has its own JavaScript variables, separate from the page’s scripts. The page can’t read your variables, and you can’t read theirs. But you both share the same DOM.

The service worker

The extension service worker runs in the background and handles browser events: a keyboard shortcut, the install event, a message from another context. It has no DOM, no window, no page.

And it doesn’t stay alive. Chrome starts it when an event arrives and stops it when it’s idle. Every global variable resets between runs. We’ll design around that in a later module.

Isolation is not a trust boundary

The isolated world protects you from accidental variable collisions. It doesn’t protect you from the page.

Both worlds read and write the same DOM. Anything your content script reads from the page markup is untrusted input. Anything you write into the page can be read by the page.

Extension storage is shared across your contexts by default, and that includes content scripts. So don’t put a secret in storage and assume the content script, which lives next to untrusted page code, can’t see it.

How contexts talk

Two mechanisms connect the pieces. Messages cross the execution boundary: the popup can ask the content script to show a panel. Storage crosses the lifetime boundary: the popup saves a note, the popup dies, the note stays.

Neither turns one context into another. The popup still can’t touch the page DOM. The worker still can’t render a form.

Before moving on, sketch Page Notes on paper. Draw three boxes with their lifetimes. Then draw the arrows: popup to storage, popup to content script, keyboard command to service worker, worker to content script. Write the payload on each arrow, and mark which values came from an untrusted page. Keep the sketch, we’ll fill it in as we build.

Lesson completed