跳到主要内容

contextMenus 右键菜单

官方文档

允许用户添加菜单项到浏览器的右键菜单中

权限设置

"permissions": [
"contextMenus"
],

方法

create() 创建菜单项

创建菜单项,如果已存在,则会更新

// 菜单项信息
type menuItemInfo = {
// 菜单项标题
title: string;
// 菜单项类型
type: 'normal' | 'checkbox' | 'radio' | 'separator';
// 菜单项图标
iconUrl: string;
// 菜单项是否可用
enabled: boolean;
// 菜单项是否可见
visible: boolean;
// 菜单项是否选中
checked: boolean;
// 菜单项子菜单
children: menuItemInfo[];
}

chrome.contextMenus.create(menuItemInfo: menuItemInfo, callback?: function);
// background.js
chrome.runtime.onInstalled.addListener(async ({ reason }) => {
if (reason !== 'install') {
return;
}

// Create an alarm so we have something to look at in the demo
await chrome.contextMenus.create({
id: 'my-menu',
title: 'My Menu',
type: 'normal',
iconUrl: 'icon-48.png',
enabled: true,
visible: true,
checked: false,
children: [
{
id: 'my-menu-1',
title: 'My Menu 1',
type: 'normal',
iconUrl: 'icon-48.png',
enabled: true,
visible: true,
checked: false,
children: [],
},
{
id: 'my-menu-2',
title: 'My Menu 2',
type: 'normal',
iconUrl: 'icon-48.png',
enabled: true,
visible: true,
checked: false,
children: [],
},
],
});
});

事件

onClicked事件

监听菜单项点击事件

// background.js
chrome.contextMenus.onClicked.addListener((info, tab) => {
console.log('🍄 background: >>>>>>>>>>>>>>>>>> 监听菜单项点击事件', Date.now(), info, tab);
});