WebView 发送消息WebView 还可以将消息传递回我们的扩展程序 。
这主要是通过使用 WebView 的 postMessage 内特殊的 VS Code API 对象上的函数来完成的 。要访问 VS Code API 对象,需要在 WebView 内部调用 acquireVsCodeApi 这个函数每个会话只能调用一次 。
而且必须保留此方法返回的 VS Code API 实例,并将其分发给任何其他需要使用它的函数 。
我们可以使用 VS Code API 的 postMessage 方法在我们的插件中显示来自 WebView 的消息:
const vscode = acquireVsCodeApi(); // 直接使用vscode.postMessage({ // 发送消息command: 'alert',text: ' 发送成功~感谢老铁~'})
我们把这个事件触发绑在了一个新的 button 上,完整的代码如下:
module.exports = (txt) => {return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Hello GitHub</title></head><body><img src=https://www.isolves.com/it/cxkf/bk/2021-09-01/"https://cdn.jsdelivr.net/gh/521xueweihan/img_logo@main/logo/readme.gif" width="300" />
hello
${txt}