If you work with webviews, you may want to open a link to a website or file within the same instance of Visual Studio Code. There are a couple of ways to achieve this, such as posting a message to the extension host or using the command URI option of your webview.
Using the command URI option involves less code and is also the preferred option. Although, you might think, why would I just not use an anchor element and set the HREF attribute to the URL? Well, there is a reason for that, which I will explain in this article.
Why can I not use a hyperlink?
When you want to use an anchor tag with a link to your website for instance, you would typically do it as follows:
|
|
It is a quick and easy way, but there is an issue. When you click on the link, it will open immediately in the browser and bypasses the outgoing link protection functionality from Visual Studio Code.
A better approach is to use an internal command like vscode.open
.
The command
The command which can be used to open links/files is vscode.open
and it can be used as follows from your extension:
|
|
To make use of internal or your commands in a webview, you need to enable the enableCommandUris
option on the webview creation.
The webview configuration
In the code where you create your webview, you can define to enable command URIs as one of the Webview/Panel options.
|
|
Once you have set this option to true
, you can use anchor tags with HREF attribute set to command:<your command>
.
The webview code
The last step is to write the code to open a link or file. To do this, you will first have to generate a Visual Studio Code URI like object, which looks as follows:
|
|
This object will be used as argument in your command URI.
Opening a link
Here is an example of how you can open a link:
|
|
infoWhen you click on the link in the webview, you will now be asked if you want to proceed opening it (if the domain is not in your trusted domains list).
Opening a file
Here is an example of how you can open a file:
|
|