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.
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.
activeWebviewPanelId value is set to the
viewType you set when creating your webview in the
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.
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.
Here is how it will look in the extension: