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