Reputation: 748
I have a list that has to be returned from the extension to the input box of my webview page.
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. How do i do this?
Upvotes: 4
Views: 7634
Reputation: 53582
The WebView class has a method to send messages to the WebView content and an event to receive messages from that. See the chapter in the vscode documenation about message passing.
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:
// 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:
(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:
currentPanel.webview.postMessage({ command: 'refactor' });
Upvotes: 13