Search code examples
visual-studio-codevscode-extensions

Can VS Code extensions get URI requests from other programs?


I found information on the official docs that onUri can be used as an activation event. So, my extension can be activated from, say, a WPF program written in C# by calling the URI such as vscode://myextension/arg1=foo&arg2=bar. But nowhere does it say how I can get the arguments that were passed with the URI request. Or even just get a raw string of it.

My question is, can it be done and if not, is there any other way to make a VS Code extension interact with another program?


Solution

  • Yes, you can use vscode.window.registerUriHandler() for this:

    Registers a uri handler capable of handling system-wide uris. In case there are multiple windows open, the topmost window will handle the uri. A uri handler is scoped to the extension it is contributed from; it will only be able to handle uris which are directed to the extension itself. A uri must respect the following rules:

    • The uri-scheme must be the vscode.env.uriScheme;
    • The uri-authority must be the extension id (eg. my.extension);
    • The uri-path, -query and -fragment parts are arbitrary.

    For example, if the my.extension extension registers a uri handler, it will only be allowed to handle uris with the prefix product-name://my.extension.

    An extension can only register a single uri handler in its entire activation lifetime.

    • Note: There is an activation event onUri that fires when a uri directed for the current extension is about to be handled.

    Usage is quite simple:

    vscode.window.registerUriHandler({
        handleUri(uri:vscode.Uri) {
            // do something with the URI
        }
    });