Popup and storage

Identify the active page

Read the current tab URL after a user gesture and turn it into a stable key for one page-specific note.

8 minute lesson

~~~

Page Notes needs the active page URL, not broad access to the user’s entire history.

The activeTab permission grants temporary access to the active tab after the user invokes the extension. Query the active tab from the popup and reject browser-internal URLs where the extension cannot run.

The grant lasts while the user remains on the same origin in that tab and is revoked when the tab closes or navigates to another origin. Opening the extension action, choosing its context-menu item, or invoking a declared command are qualifying gestures. It is a temporary capability, not a replacement for checking every result.

const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })

if (!tab.url?.startsWith('http')) {
  throw new Error('Page Notes works on web pages')
}

const key = `note:${new URL(tab.url).href}`

Decide how URL identity works before storing data. Fragments often represent position rather than a separate document, tracking parameters may be noise, and query parameters may contain private information. A normalization function should be pure and documented so saving and loading cannot disagree.

Tabs can close or navigate between the query and the next API call. Verify tab.id and URL, handle rejected promises, and show an unavailable state instead of leaving a dead form. Test a normal HTTPS page, a different query string, a fragment change, chrome://extensions, and a tab closed while the popup is open.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →