VS Code扩展开发:如何在Webview中获取当前快捷键绑定?
获取VS Code当前生效快捷键绑定的API方案
你可以使用VS Code扩展API中的
vscode.commands.getKeybindings()方法来获取当前所有生效的快捷键绑定。这个方法会返回一个Keybinding[]数组,每个元素包含命令ID、对应快捷键组合等核心信息。示例代码:
import * as vscode from 'vscode'; // 获取全部生效的快捷键绑定 const allKeybindings = vscode.commands.getKeybindings(); // 筛选你需要复用的目标快捷键(以复制命令为例) const targetBindings = allKeybindings.filter(binding => { return binding.command === 'editor.action.clipboardCopyAction'; }); // 将快捷键信息传递给Webview webviewPanel.webview.postMessage({ type: 'syncKeybindings', data: targetBindings.map(b => ({ command: b.command, displayKey: b.getLabel() // 获取可读的快捷键文本,如"Ctrl+C" })) });
- 关键说明:
getKeybindings()返回的是当前实际生效的绑定,自动处理用户自定义配置与默认配置的优先级(用户配置会覆盖默认)。- 通过
Keybinding对象的command属性匹配目标命令,用getLabel()方法获取适合展示给用户的快捷键文本。 - Webview属于独立上下文,需要通过
postMessage将快捷键信息传递过去,再在Webview的JS逻辑中监听键盘事件,匹配对应快捷键触发操作。
内容的提问来源于stack exchange,提问作者lorefnon
相关产品推荐
相关产品推荐

