【问题标题】:Calling vscode Extension for data from webview为来自 webview 的数据调用 vscode 扩展
【发布时间】:2019-07-01 06:32:01
【问题描述】:

我有一个列表,必须从扩展程序返回到我的 webview 页面的输入框。

就像 webview 中的 javascript 事件必须调用列表的扩展,然后使用该列表对象并在视图中显示列表数据。我该怎么做?

【问题讨论】:

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


    【解决方案1】:

    WebView 类有一个向 WebView 内容发送消息的方法和一个从中接收消息的事件。请参阅vscode documenation about message passing中的章节。

    在您的 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;
                }
            });
    

    在扩展代码中,您可以像这样处理来自 webview 内容的消息:

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

    要向扩展发送消息,您必须在 webview 代码中获取 vscode API:

            (function() {
                const vscode = acquireVsCodeApi();
                const counter = document.getElementById('lines-of-code-counter');
    
                let count = 0;
                setInterval(() => {
                    counter.textContent = count++;
    
                    // Alert the extension when our cat introduces a bug
                    if (Math.random() < 0.001 * count) {
                        vscode.postMessage({
                            command: 'alert',
                            text: '?  on line ' + count
                        })
                    }
                }, 100);
            }())
    

    最后,从扩展向 webview 内容发送消息非常简单:

    currentPanel.webview.postMessage({ command: 'refactor' });
    

    【讨论】:

    • 是的,我知道了,但我不需要发送消息,而是需要发送对象并在 webview 中使用它。我试过这种方式,但没有得到。
    • 您可以将该对象作为参数发送。只需在postMessage 中使用的消息对象中定义一个成员即可。然后,您可以在窗口事件侦听器中以event.data.yourObject 的身份访问它。
    • 请问为什么需要context.subscriptions 作为参数?
    • 泰铢。我不知道。这就是它在文档中的使用方式。
    猜你喜欢
    • 2021-01-03
    • 2019-03-07
    • 1970-01-01
    • 2023-01-17
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多