Skip to content

Mishka

How to add a webview in a Visual Studio Code Extension

Tutorial1 min read

Webviews display custom HTML, CSS & JS inside VS Code

It's weird how there aren't enough tutorials online for building a VS Code extension. Never have I followed any documentation this thoroughly before. I'm the one who always relies on a mix of Stackoverflow and YouTube tutorials. So it took me quite some time to figure out building a VS Code extension to save snippets.

One thing I really got stuck on was adding a webview. Users wanted to see the snippets they had saved inside VS Code. I thought a tree view would be the right fit - because the documentation scares you from using the webview API as they warn you it can slow down the application. But tree view wasn't working well.

But then I noticed a friend's VS Code extension had a webview and it was working very smoothly (Metacode, if you're interested - super fast search across your codebase). So I took a risk and added a webview to my extension. And it works perfectly. No complaints (yet!) about it slowing down anyone's computer. Here's what it looks like:

Save Code extension for VS Code

So without further rambling, here's how you add a webview to a VS Code Extension:

1. Register the command to activate the webview

In your package.json file, add a command to activate the webview function.

2. Add code to activate the webview

Now in your extension.ts (or extension.js) file, add the following code and function to open a web view.

3. Open the Webview

Now this is pretty easy. Open your webview by typing the command in the Command Palette. In this example, that would be typing and choosing "Open webview".

Viola, your webview should open up! You can also bind this command to a keyboard shortcut using the keybindings function.

4. [Optional] Link internal CSS and Javascript files to the webview

If you want to link an internal CSS stylesheet or Javascript file to the webview, you need to get the URI of those files from the context of the extension.

Add these lines of code inside the webview command:

1// Get path to resource on disk
2 const onDiskPath = vscode.Uri.file(
3 path.join(context.extensionPath, 'css', 'style.css')
4 );
5 // And get the special URI to use with the webview
6 const cssURI = panel.webview.asWebviewUri(onDiskPath);

And then pass it into the HTML of the getWebviewContent() function. Like so:

1function getWebviewContent(uri) {
2 return `<!DOCTYPE html>
3<html lang="en">
4<head>
5 <meta charset="UTF-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <link rel='stylesheet' href='`+ uri + `' /> //This is the addition
8 <title>Example Webview</title>
9</head>
10<body>
11 <h1>This works!</h1>
12 //Add some custom HTML here
13</body>
14</html>`;
15}

Hope that was helpful!


Check out the Save Code extension for VS Code: https://marketplace.visualstudio.com/items?itemName=thiscodeworks.savecode