The WebView class provides a way to communicate messages between the WebView content and receive messages. For more information on message passing, refer to the chapter in the vscode documentation.
To handle incoming messages in your webview code, you can use:
// Handle the message inside the webview
window.addEventListener('message', event => {
const message = event.data; // The JSON data sent by our extension
switch (message.command) {
case 'refactor':
count = Math.ceil(count * 0.5);
counter.textContent = count;
break;
}
});
In the extension code, you can process messages from the 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 need to access 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++;
// Notify the extension when a bug is discovered by our cat
if (Math.random() < 0.001 * count) {
vscode.postMessage({
command: 'alert',
text: '🐛 on line ' + count
})
}
}, 100);
}())
Lastly, sending a message from the extension to the webview content can be done simply with:
currentPanel.webview.postMessage({ command: 'refactor' });