← Back to blog
Tutorial · 5 min read

Chrome Extension Context Menu Tutorial

How to add right-click menu entries to a Chrome extension and handle clicks from the service worker.

Illustration for the ManifestGo article: Chrome Extension Context Menu Tutorial

Context menus are one of the highest-value, lowest-effort features you can add. Highlight text, right-click, and your extension does something useful — no popup required.

Create menus at install time

Add "contextMenus" to permissions, then create items inside chrome.runtime.onInstalled. Creating them at the top level of a service worker causes duplicate-id errors when the worker restarts.

chrome.runtime.onInstalled.addListener(() => { chrome.contextMenus.create({ id: "save-selection", title: "Save \"%s\" to my list", contexts: ["selection"] }); });

Useful contexts

  • selection — highlighted text; %s in the title is replaced by the selection.
  • link — right-click on an anchor; info.linkUrl holds the target.
  • image — info.srcUrl gives the image address.
  • page — anywhere on the page, good for a generic action.

Handling the click

chrome.contextMenus.onClicked.addListener((info, tab) => ...) runs in the service worker. Use info.menuItemId to branch, and chrome.scripting.executeScript or a message to the tab if you need page access.

Frequently asked questions

Why do I get 'Cannot create item with duplicate id'?

The service worker restarted and re-ran your create call. Wrap creation in chrome.runtime.onInstalled, or call chrome.contextMenus.removeAll() first.

Keep reading