یک منوی زمینه بسازید، یک منوی زمینه بسازید

A context menu appears for the alternate click (frequently called the right click) of a mouse. To build a context menu, first add the "contextMenus" permission to the manifest.json file.

مانیفست.json:

  "permissions": [
    "contextMenus"
  ],

در صورت تمایل، اگر می‌خواهید یک آیکون در کنار یک آیتم منو نمایش داده شود، از کلید "icons" استفاده کنید. در این مثال، آیتم منو برای افزونه "Global Google Search" از یک آیکون ۱۶ در ۱۶ استفاده می‌کند.

یک آیتم منوی زمینه با آیکون ۱۶ در ۱۶.
یک آیتم منوی زمینه با آیکون ۱۶ در ۱۶.

The rest of this example is taken from the Global Google Search context menu sample , which provides multiple context menu options. When an extension contains more than one context menu, Chrome automatically collapses them into a single parent menu as shown here:

یک منوی زمینه تو در تو.
شکل ۴ : یک منوی زمینه و یک زیرمنوی تو در تو.

این نمونه با فراخوانی تابع contextMenus.create() در سرویس دهنده افزونه ، این موضوع را نشان می‌دهد. آیتم‌های زیرمنو از فایل locales.js وارد می‌شوند. سپس runtime.onInstalled روی آنها تکرار می‌کند.

سرویس-ورکر.js:

const tldLocales = {
  'com.au': 'Australia',
  'com.br': 'Brazil',
  ...
}

chrome.runtime.onInstalled.addListener(async () => {
  for (let [tld, locale] of Object.entries(tldLocales)) {
    chrome.contextMenus.create({
      id: tld,
      title: locale,
      type: 'normal',
      contexts: ['selection'],
    });
  }
});