系统会针对鼠标交替点击(通常称为右键点击)显示上下文菜单。如需构建上下文菜单,请先向 manifest.json 文件添加 "contextMenus"
权限。
manifest.json:
"permissions": [
"contextMenus"
],
(可选)如果您想在菜单项旁边显示图标,请使用 "icons"
键。在此示例中,“全球 Google 搜索”扩展程序的菜单项使用的是 16x16 的图标。
本示例的其余部分来自全局 Google 搜索上下文菜单示例,该示例提供了多种上下文菜单选项。如果某个扩展程序包含多个上下文菜单,Chrome 会自动将其收起为一个父菜单,如下所示:
本示例通过在扩展 Service Worker 中调用 contextMenus.create()
来显示该过程。子菜单项是从 locales.js 文件导入的。然后,runtime.onInstalled
会迭代它们。
service-worker.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'],
});
}
});