How do I contribute a command to the VS Code explorer title bar or command palette that is only active when my webview is focused?

感情迁移 提交于 2019-12-08 04:48:14

问题


I'm writing an extension that uses VS Code's webview api. My extension also registers a refresh preview command that updates the webview's content. How can I make it so that:

  • The refresh preview command only shows up in the command palette when my webview is focused?

  • The refresh preview command shows in the webview's editor title bar?


回答1:


First, create a custom context key that tracks when your webview is focused. Use VS Code's setContext command to make this context key track when your webview is focused:

const myWebview = ...;

// Make the context key track when one of your webviews is focused
myWebview.onDidChangeViewState(({ webviewPanel }) => {
    vscode.commands.executeCommand('setContext',
        'myWebviewFocused',
        webviewPanel.active);
});

Then use your context key in the when clauses of your extension's menus contribution point

For a command with the id myExtension.refreshPreview, to ensure that command only shows up in the command palette when your webview is focused, use the following contribution:

{
  "contributes": {
    "menus": {
      "commandPalette": [
        {
          "command": "myExtension.refreshPreview",
          "when": "myWebviewFocused",
        }
      ]
    }
  }
}

For adding a command (possible with icon) to the editor title bar of your webview, use the editor/title contribution point:

{
  "contributes": {
    "menus": {
      "editor/title": [
        {
          "command": "myExtension.refreshPreview",
          "when": "myWebviewFocused",
        }
      ]
    }
  }
}

Check out VS Code's built-in markdown extension for a more advanced example of this.



来源:https://stackoverflow.com/questions/54917748/how-do-i-contribute-a-command-to-the-vs-code-explorer-title-bar-or-command-palet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!