javaDeveloper
javaDeveloper

Reputation: 1439

Access VS Code api from WebView

For an extension development, I am creating a webview where there are buttons in which on click of it should execute some commands in vscode (Like opening Dialog boxes)

Currently I am using React to create the WebView

Eg Code

import * as React from 'react';
import * as vscode from 'vscode'
class .... {

public render() {
<div className="some" onClick={this.function1} role="button">
                            Test
                        </div>
}

private function1() {  vscode.commands.executeCommand("commandString"); }

}

I am getting error

"Module not found: Error: Can't resolve 'vscode' in "

when running webpack

Upvotes: 0

Views: 2354

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53582

You cannot directly interact with vscode in your webview. Instead there are message APIs to send and receive (string) data. You could use that to specify a command to execute. Sending a message from the extension to the webview is described in this section.

Here's the essential part of it:

    // Handle the message inside the webview
    window.addEventListener('message', event => {

        const message = event.data; // The JSON data our extension sent

        switch (message.command) {
            case 'refactor':
                count = Math.ceil(count * 0.5);
                counter.textContent = count;
                break;
        }
    });

And for the other direction read this section.

Here's the essential part of it:

  panel.webview.onDidReceiveMessage(
    message => {
      switch (message.command) {
        case 'alert':
          vscode.window.showErrorMessage(message.text);
          return;
      }
    },
    undefined,
    context.subscriptions
  );

Upvotes: 3

Related Questions