简体   繁体   English

调用vscode Extension以从Webview获取数据

[英]Calling vscode Extension for data from webview

I have a list that has to be returned from the extension to the input box of my webview page. 我有一个列表,该列表必须从扩展名返回到Webview页面的输入框。

Its like the javascript event present in the webview has to call the extension for the list and then use that list object and show the list data in the view. 就像Web视图中存在的javascript事件一样,它必须调用列表的扩展名,然后使用该列表对象并在视图中显示列表数据。 How do i do this? 我该怎么做呢?

The WebView class has a method to send messages to the WebView content and an event to receive messages from that. WebView类具有一种将消息发送到WebView内容的方法,以及一个从中接收消息的事件。 See the chapter in the vscode documenation about message passing . 请参阅vscode文档中有关消息传递的章节。

In your webview code you can receive messages with: 在您的网络视图代码中,您可以通过以下方式接收消息:

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

In the extension code you can handle messages from your webview content like this: 在扩展代码中,您可以像这样处理来自Webview内容的消息:

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

To send a message to the extension, you have to aquire the vscode API in your webview code: 要将消息发送到扩展,您必须在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);
        }())

And finally, sending a message from the extension to the webview content is as easy as: 最后,从扩展程序向Webview内容发送消息非常简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM