Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 36 ยท Background Service Workers

Context Menus, Shortcuts and Notifications

Add right-click menu items with chrome.contextMenus, keyboard shortcuts with chrome.commands and desktop alerts with chrome.notifications, all handled by the service worker.

Three features let users reach your extension without opening a popup: the right-click menu, keyboard shortcuts and notifications. All three are handled in the service worker, which makes them a great way to practice event-driven design. We finish the chapter with a small project that combines them.

Context menus

Add "contextMenus" to permissions. Create items in onInstalled, because menu items persist across worker restarts and creating them twice raises an error.

JavaScript
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "search-selection",
    title: 'Search the web for "%s"',
    contexts: ["selection"],
  });

  chrome.contextMenus.create({
    id: "save-image",
    title: "Save image to my collection",
    contexts: ["image"],
  });

  chrome.contextMenus.create({
    id: "page-tools",
    title: "Page tools",
    contexts: ["page"],
  });
  chrome.contextMenus.create({
    id: "copy-title",
    parentId: "page-tools",
    title: "Copy page title",
    contexts: ["page"],
  });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  switch (info.menuItemId) {
    case "search-selection":
      await chrome.tabs.create({
        url: "https://www.example.com/search?q=" + encodeURIComponent(info.selectionText),
      });
      break;
    case "save-image":
      console.log("Image URL:", info.srcUrl);
      break;
  }
});

Details:

  • contexts can include page, selection, link, image, video, audio, editable, frame, action (the menu on your toolbar icon) and all.
  • %s in title is replaced by the selected text.
  • info carries menuItemId, selectionText, linkUrl, srcUrl, pageUrl; tab is the current tab.
  • Items can be type: "checkbox", "radio" or "separator"; update with chrome.contextMenus.update(id, props) and remove with remove(id).
  • Chrome groups more than one top-level item of your extension under a single parent named after the extension.
  • A menu click grants activeTab, so you can inject scripts into the clicked tab without host permissions.

Keyboard shortcuts

Declare commands in the manifest, then listen for them (see manifest fields):

JSON
"commands": {
  "toggle-highlight": {
    "suggested_key": { "default": "Alt+Shift+H", "mac": "Alt+Shift+H" },
    "description": "Toggle highlight on this page"
  }
}
JavaScript
chrome.commands.onCommand.addListener(async (command, tab) => {
  if (command === "toggle-highlight") {
    await toggleHighlight(tab);
  }
});

Rules: shortcuts must include Ctrl or Alt (Command on Mac); you may declare at most four suggested shortcuts; and the user can change or clear them at chrome://extensions/shortcuts. Use chrome.commands.getAll() to show the current binding in your UI.

Notifications

Add the "notifications" permission.

JavaScript
chrome.notifications.create("timer-done", {
  type: "basic",
  iconUrl: "icons/icon-128.png",
  title: "Time is up",
  message: "Your 25 minute focus session has ended.",
  priority: 1,
});

chrome.notifications.onClicked.addListener((id) => {
  if (id === "timer-done") chrome.tabs.create({ url: "dashboard.html" });
});

chrome.notifications.onButtonClicked.addListener((id, buttonIndex) => { /* ... */ });

type is basic, image, list or progress; iconUrl is required for basic. Operating systems may mute notifications, or show them differently (macOS and Windows both apply Focus modes), so never make a notification the only way to learn something important.

flowchart LR
    U["User action<br/>right-click, shortcut"] --> E["Service worker event"]
    E --> A["Do the work<br/>tabs, storage, scripting"]
    A --> N["Notification or badge"]
    T["Alarm"] --> E

Events in, small UI out.

Building the menu logic

You can test menu behavior without Chrome by modelling the data. This stand-in is a mini contextMenus with create, parent/child nesting and a contexts filter. It prints the menu a user would see in each context.

JS Which menu items show where?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A focus timer with a notification

The sequence "alarm fires, then notification" is the heart of many productivity extensions. Here is a stand-in you can use on this page: it uses setTimeout as an alarm, and the page's own box as the "notification" (real notifications are shown by the operating system).

Focus timer: alarm then notification

Common mistakes

Mistake Fix
contextMenus.create called on every worker start, causing "duplicate id" errors Create in onInstalled, or removeAll() first
Notification never appears Missing notifications permission, or the OS blocks Chrome's notifications
Shortcut does nothing Clash with another extension or Chrome's own shortcut; check chrome://extensions/shortcuts
Menu item shows in the wrong place Check contexts; page does not include selections or links
info.selectionText is undefined The item's contexts did not include selection

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you call chrome.contextMenus.create for permanent menu items?

    Menu items persist, so create them once on install or update to avoid duplicate-id errors.
  2. 2. What does "%s" do in a context menu item's title?

    Chrome replaces %s with the user's current text selection in the menu title.
  3. 3. Which permission is needed to show desktop notifications?

    Add "notifications" to the manifest permissions to use chrome.notifications.
  4. 4. How many suggested keyboard shortcuts can an extension declare?

    Chrome allows at most four suggested commands with keys (_execute_action counts as one).

Summary

  • Create context menu items in onInstalled and handle clicks in contextMenus.onClicked.
  • Choose contexts carefully; %s inserts the selection.
  • Commands are declared in the manifest and handled by commands.onCommand.
  • Notifications need the notifications permission and a basic type needs an icon.
  • Pair alarms with badges and notifications for background features that need no popup.

Next: One-Time Messages with runtime.sendMessage