LoginSignup
33
27

More than 3 years have passed since last update.

Chrome拡張機能で右クリックメニューを作る方法

Last updated at Posted at 2020-05-16

この記事では下記のメニュー作成のコードとクリック時のログ出力を載せています。

2020-05-16_18h40_53.png
フォルダ構造
フォルダ
 ├ manifest.json
 └ event.js
manifest.json
{
  "manifest_version": 2,
  "name": "context menus",
  "version": "1.0",

  "background": {
    "scripts": ["event.js"],
    "persistent": false
  },

  "permissions": [
    "activeTab",
    "contextMenus"
  ]
}
event.js
'use strict';

{
  chrome.runtime.onInstalled.addListener(() => {
    const parent = chrome.contextMenus.create({
      id: 'parent',
      title: '親メニュー'
    });
    chrome.contextMenus.create({
      id: 'child1',
      parentId: 'parent',
      title: '子メニュー1'
    });
    chrome.contextMenus.create({
      id: 'child2',
      parentId: 'parent',
      title: '子メニュー2'
    });
    chrome.contextMenus.create({
      id: 'child3',
      parentId: 'parent',
      title: '子メニュー3'
    });
    chrome.contextMenus.create({
      id: 'grandchild1',
      parentId: 'child1',
      title: '孫メニュー1'
    });
    chrome.contextMenus.create({
      id: 'grandchild2',
      parentId: 'child1',
      title: '孫メニュー2'
    });
  });

  // メニューをクリック時に実行
  chrome.contextMenus.onClicked.addListener(item => {
    console.log(item);
    console.log(item.menuItemId);
  });
}

孫メニュー1、子メニュー2をクリックしたときのログ

2020-05-16_18h44_57.png
孫メニュー1のログ
{editable: false, frameId: 0, menuItemId: "grandchild1", pageUrl: "https://www.google.com/?hl=ja", parentMenuItemId: "child1"}
grandchild1
子メニュー2のログ
{editable: false, frameId: 0, menuItemId: "child2", pageUrl: "https://www.google.com/?hl=ja", parentMenuItemId: "parent"}
child2

この記事はChrome拡張機能の作り方の一部のコンテンツです。

33
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
27