[vscode extension API]:如何在包含在 `vscode.previewHtml` 中的 javascript 和外部线程之间创建通信通道?
[vscode extension API]: How to create communication channel between javascript included in `vscode.previewHtml` and outside thread?
问题是,我正在尝试使用 vscode.previewHtml
命令创建一个工具,我需要一些 javascript 在其中监听用户的操作,并向外部线程发送信号,这样我可以在后台做一些高成本 "native" 的工作,并用新内容刷新 previewHtml
。
可能吗?
我假设 "outside thread" 您实际上指的是托管环境(VS 代码)。没有直接的通信方式(例如 listener/callback/method),但您可以像这样使用 postMessage
:
/* This is in a .js file you include in previewHTML. */
function exportToSVG(type) {
let html = document.querySelectorAll('html')[0];
let svg = document.querySelectorAll('svg')[0];
const args = { name: objectName, type: type, svg: svg.outerHTML, html: html.outerHTML };
window.parent.postMessage({
command: "did-click-link",
data: `command:_antlr.saveSVG?${encodeURIComponent(JSON.stringify(args))}`
}, "file://");
}
在vscode中只处理了几个命令。一个是 did-click-link
命令。然后您可以在您的扩展程序中注册该命令并执行实际工作:
// This is in your extension code (usually the activate() method).
context.subscriptions.push(commands.registerCommand('_antlr.saveSVG', (args: { name: string, type: string, svg: string, html: string }) => {
window.showInputBox({
value: workspace.getConfiguration("antlr4." + args.type)["saveDir"] + "/" + args.name + ".svg",
placeHolder: "<Enter full file name here>",
prompt: "Enter the name to an svg file."
}).then((value: string) => {
...
你可以对另一个方向使用相同的方法。例如,查看降价预览扩展如何做到这一点。
问题是,我正在尝试使用 vscode.previewHtml
命令创建一个工具,我需要一些 javascript 在其中监听用户的操作,并向外部线程发送信号,这样我可以在后台做一些高成本 "native" 的工作,并用新内容刷新 previewHtml
。
可能吗?
我假设 "outside thread" 您实际上指的是托管环境(VS 代码)。没有直接的通信方式(例如 listener/callback/method),但您可以像这样使用 postMessage
:
/* This is in a .js file you include in previewHTML. */
function exportToSVG(type) {
let html = document.querySelectorAll('html')[0];
let svg = document.querySelectorAll('svg')[0];
const args = { name: objectName, type: type, svg: svg.outerHTML, html: html.outerHTML };
window.parent.postMessage({
command: "did-click-link",
data: `command:_antlr.saveSVG?${encodeURIComponent(JSON.stringify(args))}`
}, "file://");
}
在vscode中只处理了几个命令。一个是 did-click-link
命令。然后您可以在您的扩展程序中注册该命令并执行实际工作:
// This is in your extension code (usually the activate() method).
context.subscriptions.push(commands.registerCommand('_antlr.saveSVG', (args: { name: string, type: string, svg: string, html: string }) => {
window.showInputBox({
value: workspace.getConfiguration("antlr4." + args.type)["saveDir"] + "/" + args.name + ".svg",
placeHolder: "<Enter full file name here>",
prompt: "Enter the name to an svg file."
}).then((value: string) => {
...
你可以对另一个方向使用相同的方法。例如,查看降价预览扩展如何做到这一点。