Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending a command from a virtual document in a vscode extension

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.

like image 859
Phil Giggles Avatar asked Feb 25 '26 08:02

Phil Giggles


1 Answers

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

like image 141
Matt Bierner Avatar answered Feb 28 '26 10:02

Matt Bierner