Service worker and messaging

Add a keyboard command

Declare a browser command and handle it in the service worker to open or toggle the current page note.

8 minute lesson

~~~

Keyboard commands are browser events, so they belong in the service worker rather than the short-lived popup.

Declare a command and suggested key in the manifest, then listen with chrome.commands.onCommand. Keyboard shortcuts can conflict, so provide a discoverable action and handle a missing assignment gracefully.

Suggested keys are requests, not guarantees. The browser or operating system may reserve the combination, and users can change or remove it from the extension shortcut settings. The command name in the event is the stable contract; the physical key is configuration.

A command invocation is a qualifying user gesture for activeTab, so the worker can query the active tab and inject or message it within that flow. Still reject missing IDs and restricted URLs. If no content script is present after an extension reload, initialize it deliberately before retrying the toggle once.

The worker may start only to handle this event. Read the saved note and any durable toggle state inside the listener, and make the operation idempotent. Do not assume a previous popup left the right tab or note in a global variable.

Add toggle-page-note, list its effective shortcut with chrome.commands.getAll(), and include a link or instruction for managing shortcuts. Test an assigned key, an unassigned command, a restricted page, a worker restart, and a tab that still holds an older content script.

Lesson completed

Take this course offline

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

Get the download library →