Content scripts
Inject on user action
Use chrome.scripting and activeTab to run the content script only on the page where the user requests highlighting.
8 minute lesson
Page Notes does not need to run on every website automatically. The user can ask it to highlight a saved note on the active page.
Programmatic injection combines the scripting permission with temporary host access from activeTab. It avoids broad install-time host permissions and makes the action visible and intentional.
The permission pair has separate jobs: scripting allows programmatic injection, while activeTab temporarily grants access to the invoked tab’s origin. The grant ends when the tab closes or navigates to another origin. Keep the injection inside the user-initiated flow rather than storing a tab ID and assuming access remains later.
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
})
Packaged files are easier to review and can contain reusable code. Passing func executes a serialized function and does not preserve its surrounding closure, so every dependency must be included explicitly. Choose one method and handle restricted pages, missing tab IDs, navigation races, and injection rejection.
Injection can run more than once. Make initialization idempotent by detecting the extension’s existing root or by having one installed listener handle repeated commands. Add a Highlight button, click it repeatedly, navigate during the action, and verify there is never more than one panel or an unhandled promise rejection.
Lesson completed