6.1 Context Menus

Right-Click Context Menus

Context Menusとは

右クリックメニューに独自の項目を追加できる機能。

// manifest.json
{
  "permissions": ["contextMenus"]
}

メニューの作成

// service-worker.js
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'search-selection',
    title: '「%s」を検索',
    contexts: ['selection']
  });

  chrome.contextMenus.create({
    id: 'save-image',
    title: '画像を保存',
    contexts: ['image']
  });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'search-selection') {
    const url = `https://google.com/search?q=${encodeURIComponent(info.selectionText)}`;
    chrome.tabs.create({ url });
  }
});

contextsの種類

表示条件
pageページ上どこでも
selectionテキスト選択時
linkリンク上
image画像上
video動画上
editable入力フィールド上
action拡張機能アイコン上
参考文献
[1] Chrome Extensions - chrome.contextMenus