Alert This post is over a year old, some of this information may be out of date.

How to callback to your extension from outside Visual Studio Code

While creating the authentication provider, I discovered a helpful handler in the Visual Studio Code API, which allows you to handle system-wide URIs and callback into your extension.

In the case of the authentication provider, I use it to retrieve the token that gets passed from the callback, but you can use the registerUriHandler for many more scenarios. You can, for instance, integrate a callback from your website into VS Code. Execute scripts that open a file/content you want to get processed by your extension.

How to use the registerUriHandler

It is relatively simple to create your own URI handler. All you need is the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {

  const handleUri = (uri: vscode.Uri) => {
  const queryParams = new URLSearchParams(uri.query);

    if (queryParams.has('say')) {
      vscode.window.showInformationMessage(`URI Handler says: ${queryParams.get('say') as string}`);
    }
  };

  context.subscriptions.push(
    vscode.window.registerUriHandler({
      handleUri
    })
  );
}

export function deactivate() {}
info

The logic in the handleUri is up to you/your extension.

Calling back to your extension

To trigger the handleUri method, you need to trigger it from the following URL vscode://<publisher>.<extension name>.

In the case of my example, I use the following URL: vscode://eliostruyf.vscode-urihandler-test?say=How are you doing?, which results in the subsequent notification:

Show image URI Handler showing the notification
URI Handler showing the notification

Comments

Back to top