【问题标题】:Access VS Code api from WebView从 WebView 访问 VS Code api
【发布时间】:2020-11-17 08:39:37
【问题描述】:

对于扩展开发,我正在创建一个 webview,其中有一些按钮,点击它应该在 vscode 中执行一些命令(比如打开对话框)

目前我正在使用 React 创建 WebView

例如代码

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"); }

}

我遇到错误

“未找到模块:错误:无法解析“vscode”中的“

运行 webpack 时

【问题讨论】:

    标签: typescript webpack visual-studio-code vscode-extensions


    【解决方案1】:

    您不能在 webview 中直接与 vscode 交互。取而代之的是消息 API 来发送和接收(字符串)数据。您可以使用它来指定要执行的命令。 this section 中描述了从扩展程序向 webview 发送消息。

    这是它的基本部分:

        // 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;
            }
        });
    

    而对于另一个方向阅读this section

    这是它的基本部分:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-20
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多