Alert This post is over a year old, some of this information may be out of date.

Adding editor actions for your extension webview in Visual Studio Code

In Visual Studio Code extension development, you may need a webview to give the developer/user the best experience for using your extension/functionalities.

Webviews come in different flavors. You can open them in a panel or an editor view, but there is a difference between both when it comes to showing actions or enabling/disabling commands.

When using a webview in a panel, you can use the view context key variable in the when clause of the command to get enabled/disabled.

If your webview is opened in the editor view, the view context key cannot be used. Instead, you have to add your context key(s) to inform when your webview is active and when not.

This process is a bit cumbersome and complicates it when you want, for instance, to show commands in the editor title section.

Show image Webview - Editor title commands
Webview - Editor title commands

It all changed with the release of Visual Studio Code 1.71.0. In that release, there is a new context key variable, named activeWebviewPanelId, which contains the value of the currently active webview type.

The activeWebviewPanelId value is set to the viewType you set when creating your webview in the window.createWebviewPanel method.

How to use it

If you only have one webview, it is easy to accomplish. Before, you had to set a context value to track if the webview was active or not. All you needed to do was set your context key when the webview got created and unset it when closed or navigated to another view/tab.

1
commands.executeCommand(`setContext`, `webview.active`, true);

When using multiple webviews, you had to ensure not to unsettle the context key when navigating from one to another.

With the availability of the new activeWebviewPanelId context key, all you need to do is use it in the when clause command you want to enable/disable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
{
  "contributes": {
    ...
    "menus": {
      "editor/title": [
        {
          "command": "vscode-rapidapi-client.request.fullView",
          "group": "navigation",
          "when": "activeWebviewPanelId == '<viewType value>'"
        }
      ]
    }
  }
}

Here is how it will look in the extension:

Show image Webview - Custom command enabled in editor&#x2F;title
Webview - Custom command enabled in editor&#x2F;title

Comments

Back to top