Sending command from virtual document to vscode extension

I am making a Visual Studio Code extension where I create a virtual document

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

      

And I will register the command with:

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

      

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

If I have a link in a virtual document like:

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

      

It calls the command, but the message is undefined. This is how I understood it.

I don't want to call it by reference, I want to send a message using TypeScript from a Polymer (v2) method in a virtual document.

+2


source to share


1 answer


Command arguments should be passed as 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 for sending commands back to the editor programmatically, but you can use the built-in label extension method :

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

      

Not really, but it works

+2


source







All Articles