右键菜单
注意
v2.2 开始支持。
利用 WebView2 原生上下文菜单 API,实现类似 Electron 的右键菜单自定义系统。
事件
右键菜单事件(context-menu)
右键点击时自动触发(需 allow_right_click=1),event_data 为 JSON。
window_id:触发事件的窗口ID。
event_data:JSON,包含右键目标的详细信息:
{
"x": 100, "y": 200,
"kind": "page",
"is_editable": false, "is_main_frame": true,
"page_url": "https://example.com", "frame_url": "",
"has_link": true, "link_url": "https://example.com/page2", "link_text": "点击这里",
"has_source": false, "source_url": "",
"has_selection": true, "selection_text": "选中文本",
"default_menu_names": [
{"name": "back", "label": "后退(&B)", "kind": "command"},
{"name": "forward", "label": "前进(&F)", "kind": "command"},
{"name": "other", "label": "", "kind": "separator"}
]
}
| 字段 | 说明 |
|---|---|
x / y | 屏幕坐标 |
kind | 目标类型:page / image / selected_text / audio / video |
is_editable | 是否可编辑区域 |
is_main_frame | 是否在主框架中 |
page_url / frame_url | 页面/框架 URL |
has_link / link_url / link_text | 链接信息 |
has_source / source_url | 资源源信息(图片/音视频) |
has_selection / selection_text | 选中文本信息 |
default_menu_names (2.2 新增) | WebView2 默认菜单项列表,每项含 name、label、kind(见 菜单项类型与原生菜单项) |
菜单项点击事件(menu-item-clicked)
自定义菜单项被点击时触发,event_data 为创建时传入的 item_id(字符串)。
window_id:触发事件的窗口ID。
event_data:创建菜单项时传入的 item_id 字符串。
C API
创建菜单项(jade_menu_item_create)
uint32_t jade_menu_item_create(const char* label, int kind, uint32_t parent_menu_id, int item_id);
参数:
labelstring- 菜单项文本(kind=5时填 WebView2 默认菜单项的 Name,如"copy")kindint- 菜单项类型(见下表)parent_menu_iduint32_t- 父菜单ID(0= 顶级菜单,>0= 添加到指定子菜单)item_idint- 用户自定义ID,点击时通过menu-item-clicked事件返回(kind=5忽略此参数)
返回值:
> 0- 菜单项ID(menu_id)0- 失败
kind 参数说明
菜单项类型说明、kind=5 默认菜单项的 WebView2 原生 Name 列表(按右键上下文分类)详见 菜单项类型与原生菜单项。
设置菜单项启用状态(jade_menu_item_set_enabled)
int jade_menu_item_set_enabled(uint32_t menu_id, int enabled);
参数:
menu_iduint32_t- 菜单项IDenabledint-0= 禁用,1= 启用
返回值: 1 = 成功,0 = 失败
设置菜单项选中状态(jade_menu_item_set_checked)
int jade_menu_item_set_checked(uint32_t menu_id, int checked);
参数:
menu_iduint32_t- 菜单项IDcheckedint-0= 未选中,1= 选中
返回值: 1 = 成功,0 = 失败
设置右键菜单项(jade_set_context_menu_items)
在 context-menu 事件回调中调用,设置要显示的菜单项。
int jade_set_context_menu_items(uint32_t window_id, const uint32_t* menu_ids, int count);
参数:
window_iduint32_t- 窗口IDmenu_idsuint32_t*- 菜单项ID数组countint- 数组长度
返回值: 1 = 成功,0 = 失败
销毁菜单项(jade_menu_item_destroy)
int jade_menu_item_destroy(uint32_t menu_id);
参数:
menu_iduint32_t- 菜单项ID
返回值: 1 = 成功,0 = 失败
使用流程
- 注册
context-menu事件监听:jade_on("context-menu", callback) - 在回调中,根据
kind等字段判断右键目标 - 调用
jade_menu_item_create创建菜单项 - 调用
jade_set_context_menu_items设置要显示的菜单 - WebView2 自动弹出原生菜单
- 用户点击后,
menu-item-clicked事件返回item_id
备注
如果不注册 context-menu 事件监听,右键将显示 WebView2 默认菜单。