sending a command from a virtual document in a vscode extension

匆匆过客 提交于 2020-01-02 10:23:09

问题


I am making a Visual Studio Code extension, where I make a virtual document

let provider = new TextDocumentContentProvider();
let registration = vscode.workspace.registerTextDocumentContentProvider('nucleus-preview', provider);

And I register a command with:

vscode.commands.registerCommand('extension.sendMessage', (message) => {
    console.log('the message is ', message)
});

In the virtual document I want to send a message back to the extension using JavaScript.

If I have a link in the virtual document like such:

<a href="command:extension.sayHi?message=hi">say Hi</a>

It calls the command but the message is undefined. That's as far as I got.

I don't want to call it using a link, I want to send the message using TypeScript from a method of a Polymer Element (v2) in the virtual doc.


回答1:


The command arguments needs to be passed as an encoded json array instead of parameters:

command:extension.sayHi?%5B%22hi%22%5D

Try using a helper function like:

const createCommandUri = (name, ...args) =>
    `command:${name}?${encodeURIComponent(JSON.stringify(args))}`

We don't have an official API to send commands back to the editor programmatically, but you can use the built-in markdown extension's method:

window.parent.postMessage({
    command: "did-click-link",
    data: createCommandUri('extension.sendMessage', 'hi')
}, "file://")

Not great but it works



来源:https://stackoverflow.com/questions/45481546/sending-a-command-from-a-virtual-document-in-a-vscode-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!