Webview API

The webview API allows extensions to create fully customizable views within Visual Studio Code. For example, the built-in Markdown extension uses webviews to render Markdown previews. Webviews can also be used to build complex user interfaces beyond what VS Code’s native APIs support.

Think of a webview as an iframe within VS Code that your extension controls. A webview can render almost any HTML content in this frame, and it communicates with extensions using message passing. This freedom makes webviews incredibly powerful, and opens up a whole new range of extension possibilities.

Webviews are used in few VS Code API:

  • With Webview Panels created using createWebviewPanel. In this case, Webview panels are shown in VS Code as distinct editors. This makes them useful for displaying custom UI and custom visualizations.
  • As the view for a custom editor. Custom editors allow extensions to provide a custom UI for editing any file in the workspace. The custom editor API also lets your extension hook into editor events such as undo and redo, as well as file events such as save.
  • In Webview views that are rendered in the sidebar or panel areas. See the webview view sample extension for more details.

This page focuses on the basic webview panel API, although almost everything covered here applies to the webviews used in custom editors and webview views as well. Even if you are more interested in those APIs, we recommend reading through this page first to familiarize yourself with the webview basics.

Links

VS Code API Usage

Should I use a webview?

Webviews are pretty amazing, but they should also be used sparingly and only when VS Code’s native API is inadequate. Webviews are resource heavy and run in a separate context from normal extensions. A poorly designed webview can also easily feel out of place within VS Code.

Before using a webview, please consider the following:

  • Does this functionality really need to live within VS Code? Would it be better as a separate application or website?

  • Is a webview the only way to implement your feature? Can you use the regular VS Code APIs instead?

  • Will your webview add enough user value to justify its high resource cost?

Remember: Just because you can do something with webviews, doesn’t mean you should. However, if you are confident that you need to use webviews, then this document is here to help. Let’s get started.

Webviews API basics

To explain the webview API, we are going to build a simple extension called Cat Coding. This extension will use a webview to show a gif of a cat writing some code (presumably in VS Code). As we work through the API, we’ll continue adding functionality to the extension, including a counter that keeps track of how many lines of source code our cat has written and notifications that inform the user when the cat introduces a bug.

Here’s the package.json for the first version of the Cat Coding extension. You can find the complete code for the example app here. The first version of our extension contributes a command called catCoding.start. When a user invokes this command, we will show a simple webview with our cat in it. Users will be able to invoke this command from the Command Palette as Cat Coding: Start new cat coding session or even create a keybinding for it if they are so inclined.

  1. {
  2. "name": "cat-coding",
  3. "description": "Cat Coding",
  4. "version": "0.0.1",
  5. "publisher": "bierner",
  6. "engines": {
  7. "vscode": "^1.23.0"
  8. },
  9. "activationEvents": ["onCommand:catCoding.start"],
  10. "main": "./out/src/extension",
  11. "contributes": {
  12. "commands": [
  13. {
  14. "command": "catCoding.start",
  15. "title": "Start new cat coding session",
  16. "category": "Cat Coding"
  17. }
  18. ]
  19. },
  20. "scripts": {
  21. "vscode:prepublish": "tsc -p ./",
  22. "compile": "tsc -watch -p ./",
  23. "postinstall": "node ./node_modules/vscode/bin/install"
  24. },
  25. "dependencies": {
  26. "vscode": "*"
  27. },
  28. "devDependencies": {
  29. "@types/node": "^9.4.6",
  30. "typescript": "^2.8.3"
  31. }
  32. }

Now let’s implement the catCoding.start command. In our extension’s main file, we register the catCoding.start command and use it to show a basic webview:

  1. import * as vscode from 'vscode';
  2. export function activate(context: vscode.ExtensionContext) {
  3. context.subscriptions.push(
  4. vscode.commands.registerCommand('catCoding.start', () => {
  5. // Create and show a new webview
  6. const panel = vscode.window.createWebviewPanel(
  7. 'catCoding', // Identifies the type of the webview. Used internally
  8. 'Cat Coding', // Title of the panel displayed to the user
  9. vscode.ViewColumn.One, // Editor column to show the new webview panel in.
  10. {} // Webview options. More on these later.
  11. );
  12. })
  13. );
  14. }

The vscode.window.createWebviewPanel function creates and shows a webview in the editor. Here is what you see if you try running the catCoding.start command in its current state:

An empty webview

Our command opens a new webview panel with the correct title, but with no content! To add our cat to new panel, we also need to set the HTML content of the webview using webview.html:

  1. import * as vscode from 'vscode';
  2. export function activate(context: vscode.ExtensionContext) {
  3. context.subscriptions.push(
  4. vscode.commands.registerCommand('catCoding.start', () => {
  5. // Create and show panel
  6. const panel = vscode.window.createWebviewPanel(
  7. 'catCoding',
  8. 'Cat Coding',
  9. vscode.ViewColumn.One,
  10. {}
  11. );
  12. // And set its HTML content
  13. panel.webview.html = getWebviewContent();
  14. })
  15. );
  16. }
  17. function getWebviewContent() {
  18. return `<!DOCTYPE html>
  19. <html lang="en">
  20. <head>
  21. <meta charset="UTF-8">
  22. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  23. <title>Cat Coding</title>
  24. </head>
  25. <body>
  26. <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
  27. </body>
  28. </html>`;
  29. }

If you run the command again, now the webview looks like this:

A webview with some HTML

Progress!

webview.html should always be a complete HTML document. HTML fragments or malformed HTML may cause unexpected behavior.

Updating webview content

webview.html can also update a webview’s content after it has been created. Let’s use this to make Cat Coding more dynamic by introducing a rotation of cats:

  1. import * as vscode from 'vscode';
  2. const cats = {
  3. 'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  4. 'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
  5. };
  6. export function activate(context: vscode.ExtensionContext) {
  7. context.subscriptions.push(
  8. vscode.commands.registerCommand('catCoding.start', () => {
  9. const panel = vscode.window.createWebviewPanel(
  10. 'catCoding',
  11. 'Cat Coding',
  12. vscode.ViewColumn.One,
  13. {}
  14. );
  15. let iteration = 0;
  16. const updateWebview = () => {
  17. const cat = iteration++ % 2 ? 'Compiling Cat' : 'Coding Cat';
  18. panel.title = cat;
  19. panel.webview.html = getWebviewContent(cat);
  20. };
  21. // Set initial content
  22. updateWebview();
  23. // And schedule updates to the content every second
  24. setInterval(updateWebview, 1000);
  25. })
  26. );
  27. }
  28. function getWebviewContent(cat: keyof typeof cats) {
  29. return `<!DOCTYPE html>
  30. <html lang="en">
  31. <head>
  32. <meta charset="UTF-8">
  33. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  34. <title>Cat Coding</title>
  35. </head>
  36. <body>
  37. <img src="${cats[cat]}" width="300" />
  38. </body>
  39. </html>`;
  40. }

Updating the webview content

Setting webview.html replaces the entire webview content, similar to reloading an iframe. This is important to remember once you start using scripts in a webview, since it means that setting webview.html also resets the script’s state.

The example above also uses webview.title to change the title of the document displayed in the editor. Setting the title does not cause the webview to be reloaded.

Lifecycle

Webview panels are owned by the extension that creates them. The extension must hold onto the webview returned from createWebviewPanel. If your extension loses this reference, it cannot regain access to that webview again, even though the webview will continue to show in VS Code.

As with text editors, a user can also close a webview panel at any time. When a webview panel is closed by the user, the webview itself is destroyed. Attempting to use a destroyed webview throws an exception. This means that the example above using setInterval actually has an important bug: if the user closes the panel, setInterval will continue to fire, which will try to update panel.webview.html, which of course will throw an exception. Cats hate exceptions. Let’s fix this!

The onDidDispose event is fired when a webview is destroyed. We can use this event to cancel further updates and clean up the webview’s resources:

  1. import * as vscode from 'vscode';
  2. const cats = {
  3. 'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  4. 'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
  5. };
  6. export function activate(context: vscode.ExtensionContext) {
  7. context.subscriptions.push(
  8. vscode.commands.registerCommand('catCoding.start', () => {
  9. const panel = vscode.window.createWebviewPanel(
  10. 'catCoding',
  11. 'Cat Coding',
  12. vscode.ViewColumn.One,
  13. {}
  14. );
  15. let iteration = 0;
  16. const updateWebview = () => {
  17. const cat = iteration++ % 2 ? 'Compiling Cat' : 'Coding Cat';
  18. panel.title = cat;
  19. panel.webview.html = getWebviewContent(cat);
  20. };
  21. updateWebview();
  22. const interval = setInterval(updateWebview, 1000);
  23. panel.onDidDispose(
  24. () => {
  25. // When the panel is closed, cancel any future updates to the webview content
  26. clearInterval(interval);
  27. },
  28. null,
  29. context.subscriptions
  30. );
  31. })
  32. );
  33. }

Extensions can also programmatically close webviews by calling dispose() on them. If, for example, we wanted to restrict our cat’s workday to five seconds:

  1. export function activate(context: vscode.ExtensionContext) {
  2. context.subscriptions.push(
  3. vscode.commands.registerCommand('catCoding.start', () => {
  4. const panel = vscode.window.createWebviewPanel(
  5. 'catCoding',
  6. 'Cat Coding',
  7. vscode.ViewColumn.One,
  8. {}
  9. );
  10. panel.webview.html = getWebviewContent(cats['Coding Cat']);
  11. // After 5sec, pragmatically close the webview panel
  12. const timeout = setTimeout(() => panel.dispose(), 5000);
  13. panel.onDidDispose(
  14. () => {
  15. // Handle user closing panel before the 5sec have passed
  16. clearTimeout(timeout);
  17. },
  18. null,
  19. context.subscriptions
  20. );
  21. })
  22. );
  23. }

Visibility and Moving

When a webview panel is moved into a background tab, it becomes hidden. It is not destroyed however. VS Code will automatically restore the webview’s content from webview.html when the panel is brought to the foreground again:

Webview content is automatically restored when the webview becomes visible again

The .visible property tells you if the webview panel is currently visible or not.

Extensions can programmatically bring a webview panel to the foreground by calling reveal(). This method takes an optional target view column to show the panel in. A webview panel may only show in a single editor column at a time. Calling reveal() or dragging a webview panel to a new editor column moves the webview into that new column.

Webviews are moved when you drag them between tabs

Let’s update our extension to only allow a single webview to exist at a time. If the panel is in the background, then the catCoding.start command will bring it to the foreground:

  1. export function activate(context: vscode.ExtensionContext) {
  2. // Track currently webview panel
  3. let currentPanel: vscode.WebviewPanel | undefined = undefined;
  4. context.subscriptions.push(
  5. vscode.commands.registerCommand('catCoding.start', () => {
  6. const columnToShowIn = vscode.window.activeTextEditor
  7. ? vscode.window.activeTextEditor.viewColumn
  8. : undefined;
  9. if (currentPanel) {
  10. // If we already have a panel, show it in the target column
  11. currentPanel.reveal(columnToShowIn);
  12. } else {
  13. // Otherwise, create a new panel
  14. currentPanel = vscode.window.createWebviewPanel(
  15. 'catCoding',
  16. 'Cat Coding',
  17. columnToShowIn,
  18. {}
  19. );
  20. currentPanel.webview.html = getWebviewContent(cats['Coding Cat']);
  21. // Reset when the current panel is closed
  22. currentPanel.onDidDispose(
  23. () => {
  24. currentPanel = undefined;
  25. },
  26. null,
  27. context.subscriptions
  28. );
  29. }
  30. })
  31. );
  32. }

Here’s the new extension in action:

Using a single panel and reveal

Whenever a webview’s visibility changes, or when a webview is moved into a new column, the onDidChangeViewState event is fired. Our extension can use this event to change cats based on which column the webview is showing in:

  1. const cats = {
  2. 'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
  3. 'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
  4. 'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
  5. };
  6. export function activate(context: vscode.ExtensionContext) {
  7. context.subscriptions.push(
  8. vscode.commands.registerCommand('catCoding.start', () => {
  9. const panel = vscode.window.createWebviewPanel(
  10. 'catCoding',
  11. 'Cat Coding',
  12. vscode.ViewColumn.One,
  13. {}
  14. );
  15. panel.webview.html = getWebviewContent(cats['Coding Cat']);
  16. // Update contents based on view state changes
  17. panel.onDidChangeViewState(
  18. e => {
  19. const panel = e.webviewPanel;
  20. switch (panel.viewColumn) {
  21. case vscode.ViewColumn.One:
  22. updateWebviewForCat(panel, 'Coding Cat');
  23. return;
  24. case vscode.ViewColumn.Two:
  25. updateWebviewForCat(panel, 'Compiling Cat');
  26. return;
  27. case vscode.ViewColumn.Three:
  28. updateWebviewForCat(panel, 'Testing Cat');
  29. return;
  30. }
  31. },
  32. null,
  33. context.subscriptions
  34. );
  35. })
  36. );
  37. }
  38. function updateWebviewForCat(panel: vscode.WebviewPanel, catName: keyof typeof cats) {
  39. panel.title = catName;
  40. panel.webview.html = getWebviewContent(cats[catName]);
  41. }

Responding to onDidChangeViewState events

Inspecting and debugging webviews

The Developer: Open Webview Developer Tools VS Code command lets you debug webviews. Running the command launches an instance of Developer Tools for any currently visible webviews:

Webview Developer Tools

The contents of the webview are within an iframe inside the webview document. You can use Developer Tools to inspect and modify the webview’s DOM, and debug scripts running within the webview itself.

If you use the webview Developer Tools console, make sure to select the active frame environment from the drop-down in the top left corner of the Console panel:

Selecting the active frame

The active frame environment is where the webview scripts themselves are executed.

In addition, the Developer: Reload Webview command reloads all active webviews. This can be helpful if you need to reset a webview’s state, or if some webview content on disk has changed and you want the new content to be loaded.

Loading local content

Webviews run in isolated contexts that cannot directly access local resources. This is done for security reasons. This means that in order to load images, stylesheets, and other resources from your extension, or to load any content from the user’s current workspace, you must use the Webview.asWebviewUri function to convert a local file: URI into a special URI that VS Code can use to load a subset of local resources.

Imagine that we want to start bundling the cat gifs into our extension rather pulling them from Giphy. To do this, we first create a URI to the file on disk and then pass these URIs through the asWebviewUri function:

  1. import * as vscode from 'vscode';
  2. import * as path from 'path';
  3. export function activate(context: vscode.ExtensionContext) {
  4. context.subscriptions.push(
  5. vscode.commands.registerCommand('catCoding.start', () => {
  6. const panel = vscode.window.createWebviewPanel(
  7. 'catCoding',
  8. 'Cat Coding',
  9. vscode.ViewColumn.One,
  10. {}
  11. );
  12. // Get path to resource on disk
  13. const onDiskPath = vscode.Uri.file(
  14. path.join(context.extensionPath, 'media', 'cat.gif')
  15. );
  16. // And get the special URI to use with the webview
  17. const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
  18. panel.webview.html = getWebviewContent(catGifSrc);
  19. })
  20. );
  21. }

If we debug this code, we’d see that the actual value for catGifSrc is something like:

  1. vscode-resource:/Users/toonces/projects/vscode-cat-coding/media/cat.gif

VS Code understands this special URI and will use it to load our gif from the disk!

By default, webviews can only access resources in the following locations:

  • Within your extension’s install directory.
  • Within the user’s currently active workspace.

Use the WebviewOptions.localResourceRoots to allow access to additional local resources.

You can also always use data URIs to embed resources directly within the webview.

Controlling access to local resources

Webviews can control which resources can be loaded from the user’s machine with localResourceRoots option. localResourceRoots defines a set of root URIs from which local content may be loaded.

We can use localResourceRoots to restrict Cat Coding webviews to only load resources from a media directory in our extension:

  1. import * as vscode from 'vscode';
  2. import * as path from 'path';
  3. export function activate(context: vscode.ExtensionContext) {
  4. context.subscriptions.push(
  5. vscode.commands.registerCommand('catCoding.start', () => {
  6. const panel = vscode.window.createWebviewPanel(
  7. 'catCoding',
  8. 'Cat Coding',
  9. vscode.ViewColumn.One,
  10. {
  11. // Only allow the webview to access resources in our extension's media directory
  12. localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'media'))]
  13. }
  14. );
  15. const onDiskPath = vscode.Uri.file(
  16. path.join(context.extensionPath, 'media', 'cat.gif')
  17. );
  18. const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
  19. panel.webview.html = getWebviewContent(catGifSrc);
  20. })
  21. );
  22. }

To disallow all local resources, just set localResourceRoots to [].

In general, webviews should be as restrictive as possible in loading local resources. However, keep in mind that localResourceRoots does not offer complete security protection on its own. Make sure your webview also follows security best practices, and add a content security policy to further restrict the content that can be loaded.

Theming webview content

Webview can use CSS to change their appearance based on VS Code’s current theme. VS Code groups themes into three categories, and adds a special class to the body element to indicate the current theme:

  • vscode-light - Light themes.
  • vscode-dark - Dark themes.
  • vscode-high-contrast - High contrast themes.

The following CSS changes the text color of the webview based on the user’s current theme:

  1. body.vscode-light {
  2. color: black;
  3. }
  4. body.vscode-dark {
  5. color: white;
  6. }
  7. body.vscode-high-contrast {
  8. color: red;
  9. }

When developing a webview application, make sure that it works for the three types of themes. And always test your webview in high-contrast mode to make sure it will be usable by people with visual disabilities.

Webviews can also access VS Code theme colors using CSS variables. These variable names are prefixed with vscode and replace the . with -. For example editor.foreground becomes var(--vscode-editor-foreground):

  1. code {
  2. color: var(--vscode-editor-foreground);
  3. }

Review the Theme Color Reference for the available theme variables. An extension is available which provides IntelliSense suggestions for the variables.

The following font related variables are also defined:

  • --vscode-editor-font-family - Editor font family (from the editor.fontFamily setting).
  • --vscode-editor-font-weight - Editor font weight (from the editor.fontWeight setting).
  • --vscode-editor-font-size - Editor font size (from the editor.fontSize setting).

Finally, for special cases where you need to write CSS that targets a single theme, the body element of webviews has a new data attribute called vscode-theme-name that stores the full name of the currently active theme. This lets you write theme-specific CSS for webviews:

  1. body[data-vscode-theme-name="One Dark Pro"] {
  2. background: hotpink;
  3. }

Scripts and message passing

Webviews are just like iframes, which means that they can also run scripts. JavaScript is disabled in webviews by default, but it can easily re-enable by passing in the enableScripts: true option.

Let’s use a script to add a counter tracking the lines of source code our cat has written. Running a basic script is pretty simple, but note that this example is only for demonstration purposes. In practice, your webview should always disable inline scripts using a content security policy:

  1. import * as path from 'path';
  2. import * as vscode from 'vscode';
  3. export function activate(context: vscode.ExtensionContext) {
  4. context.subscriptions.push(
  5. vscode.commands.registerCommand('catCoding.start', () => {
  6. const panel = vscode.window.createWebviewPanel(
  7. 'catCoding',
  8. 'Cat Coding',
  9. vscode.ViewColumn.One,
  10. {
  11. // Enable scripts in the webview
  12. enableScripts: true
  13. }
  14. );
  15. panel.webview.html = getWebviewContent();
  16. })
  17. );
  18. }
  19. function getWebviewContent() {
  20. return `<!DOCTYPE html>
  21. <html lang="en">
  22. <head>
  23. <meta charset="UTF-8">
  24. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  25. <title>Cat Coding</title>
  26. </head>
  27. <body>
  28. <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
  29. <h1 id="lines-of-code-counter">0</h1>
  30. <script>
  31. const counter = document.getElementById('lines-of-code-counter');
  32. let count = 0;
  33. setInterval(() => {
  34. counter.textContent = count++;
  35. }, 100);
  36. </script>
  37. </body>
  38. </html>`;
  39. }

A script running in a webview

Wow! that’s one productive cat.

Webview scripts can do just about anything that a script on a normal webpage can. Keep in mind though that webviews exist in their own context, so scripts in a webview do not have access to the VS Code API. That’s where message passing comes in!

Passing messages from an extension to a webview

An extension can send data to its webviews using webview.postMessage(). This method sends any JSON serializable data to the webview. The message is received inside the webview through the standard message event.

To demonstrate this, let’s add a new command to Cat Coding that instructs the currently coding cat to refactor their code (thereby reducing the total number of lines). The new catCoding.doRefactor command use postMessage to send the instruction to the current webview, and window.addEventListener('message', event => { ... }) inside the webview itself to handle the message:

  1. export function activate(context: vscode.ExtensionContext) {
  2. // Only allow a single Cat Coder
  3. let currentPanel: vscode.WebviewPanel | undefined = undefined;
  4. context.subscriptions.push(
  5. vscode.commands.registerCommand('catCoding.start', () => {
  6. if (currentPanel) {
  7. currentPanel.reveal(vscode.ViewColumn.One);
  8. } else {
  9. currentPanel = vscode.window.createWebviewPanel(
  10. 'catCoding',
  11. 'Cat Coding',
  12. vscode.ViewColumn.One,
  13. {
  14. enableScripts: true
  15. }
  16. );
  17. currentPanel.webview.html = getWebviewContent();
  18. currentPanel.onDidDispose(
  19. () => {
  20. currentPanel = undefined;
  21. },
  22. undefined,
  23. context.subscriptions
  24. );
  25. }
  26. })
  27. );
  28. // Our new command
  29. context.subscriptions.push(
  30. vscode.commands.registerCommand('catCoding.doRefactor', () => {
  31. if (!currentPanel) {
  32. return;
  33. }
  34. // Send a message to our webview.
  35. // You can send any JSON serializable data.
  36. currentPanel.webview.postMessage({ command: 'refactor' });
  37. })
  38. );
  39. }
  40. function getWebviewContent() {
  41. return `<!DOCTYPE html>
  42. <html lang="en">
  43. <head>
  44. <meta charset="UTF-8">
  45. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  46. <title>Cat Coding</title>
  47. </head>
  48. <body>
  49. <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
  50. <h1 id="lines-of-code-counter">0</h1>
  51. <script>
  52. const counter = document.getElementById('lines-of-code-counter');
  53. let count = 0;
  54. setInterval(() => {
  55. counter.textContent = count++;
  56. }, 100);
  57. // Handle the message inside the webview
  58. window.addEventListener('message', event => {
  59. const message = event.data; // The JSON data our extension sent
  60. switch (message.command) {
  61. case 'refactor':
  62. count = Math.ceil(count * 0.5);
  63. counter.textContent = count;
  64. break;
  65. }
  66. });
  67. </script>
  68. </body>
  69. </html>`;
  70. }

Passing messages to a webview

Passing messages from a webview to an extension

Webviews can also pass messages back to their extension. This is accomplished using a postMessage function on a special VS Code API object inside the webview. To access the VS Code API object, call acquireVsCodeApi inside the webview. This function can only be invoked once per session. You must hang onto the instance of the VS Code API returned by this method, and hand it out to any other functions that wish to use it.

We can use the VS Code API and postMessage in our Cat Coding webview to alert the extension when our cat introduces a bug in their code:

  1. export function activate(context: vscode.ExtensionContext) {
  2. context.subscriptions.push(
  3. vscode.commands.registerCommand('catCoding.start', () => {
  4. const panel = vscode.window.createWebviewPanel(
  5. 'catCoding',
  6. 'Cat Coding',
  7. vscode.ViewColumn.One,
  8. {
  9. enableScripts: true
  10. }
  11. );
  12. panel.webview.html = getWebviewContent();
  13. // Handle messages from the webview
  14. panel.webview.onDidReceiveMessage(
  15. message => {
  16. switch (message.command) {
  17. case 'alert':
  18. vscode.window.showErrorMessage(message.text);
  19. return;
  20. }
  21. },
  22. undefined,
  23. context.subscriptions
  24. );
  25. })
  26. );
  27. }
  28. function getWebviewContent() {
  29. return `<!DOCTYPE html>
  30. <html lang="en">
  31. <head>
  32. <meta charset="UTF-8">
  33. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  34. <title>Cat Coding</title>
  35. </head>
  36. <body>
  37. <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
  38. <h1 id="lines-of-code-counter">0</h1>
  39. <script>
  40. (function() {
  41. const vscode = acquireVsCodeApi();
  42. const counter = document.getElementById('lines-of-code-counter');
  43. let count = 0;
  44. setInterval(() => {
  45. counter.textContent = count++;
  46. // Alert the extension when our cat introduces a bug
  47. if (Math.random() < 0.001 * count) {
  48. vscode.postMessage({
  49. command: 'alert',
  50. text: '🐛 on line ' + count
  51. })
  52. }
  53. }, 100);
  54. }())
  55. </script>
  56. </body>
  57. </html>`;
  58. }

Passing messages from the webview to the main extension

For security reasons, you must keep the VS Code API object private and make sure it is never leaked into the global scope.

Security

As with any webpage, when creating a webview you must follow some basic security best practices.

Limit capabilities

A webview should have the minimum set of capabilities that it needs. For example, if your webview does not need to run scripts, do not set the enableScripts: true. If your webview does not need to load resources from the user’s workspace, set localResourceRoots to [vscode.Uri.file(extensionContext.extensionPath)] or even [] to disallow access to all local resources.

Content security policy

Content security policies further restrict the content that can be loaded and executed in webviews. For example, a content security policy can make sure that only a list of allowed scripts can be run in the webview, or even tell the webview to only load images over https.

To add a content security policy, put a <meta http-equiv="Content-Security-Policy"> directive at the top of the webview’s <head>

  1. function getWebviewContent() {
  2. return `<!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta http-equiv="Content-Security-Policy" content="default-src 'none';">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>Cat Coding</title>
  9. </head>
  10. <body>
  11. ...
  12. </body>
  13. </html>`;
  14. }

The policy default-src 'none'; disallows all content. We can then turn back on the minimal amount of content that our extension needs to function. Here’s a content security policy that allows loading local scripts and stylesheets, and loading images over https:

  1. <meta
  2. http-equiv="Content-Security-Policy"
  3. content="default-src 'none'; img-src ${webview.cspSource} https:; script-src ${webview.cspSource}; style-src ${webview.cspSource};"
  4. />

The ${webview.cspSource} value is a placeholder for a value that comes from the webview object itself. See the webview sample for a complete example of how to use this value.

This content security policy also implicitly disables inline scripts and styles. It is a best practice to extract all inline styles and scripts to external files so that they can be properly loaded without relaxing the content security policy.

Only load content over https

If your webview allows loading external resources, it is strongly recommended that you only allow these resources to be loaded over https and not over http. The example content security policy above already does this by only allowing images to be loaded over https:.

Sanitize all user input

Just as you would for a normal webpage, when constructing the HTML for a webview, you must sanitize all user input. Failing to properly sanitize input can allow content injections, which may open your users up to a security risk.

Example values that must be sanitized:

  • File contents.
  • File and folder paths.
  • User and workspace settings.

Consider using a helper library to construct your HTML strings, or at least ensure that all content from the user’s workspace is properly sanitized.

Never rely on sanitization alone for security. Make sure to follow the other security best practices, such as having a content security policy to minimize the impact of any potential content injections.

Persistence

In the standard webview lifecycle, webviews are created by createWebviewPanel and destroyed when the user closes them or when .dispose() is called. The contents of webviews however are created when the webview becomes visible and destroyed when the webview is moved into the background. Any state inside the webview will be lost when the webview is moved to a background tab.

The best way to solve this is to make your webview stateless. Use message passing to save off the webview’s state and then restore the state when the webview becomes visible again.

getState and setState

Scripts running inside a webview can use the getState and setState methods to save off and restore a JSON serializable state object. This state is persisted even the webview content itself is destroyed when a webview panel becomes hidden. The state is destroyed when the webview panel is destroyed.

  1. // Inside a webview script
  2. const vscode = acquireVsCodeApi();
  3. const counter = document.getElementById('lines-of-code-counter');
  4. // Check if we have an old state to restore from
  5. const previousState = vscode.getState();
  6. let count = previousState ? previousState.count : 0;
  7. counter.textContent = count;
  8. setInterval(() => {
  9. counter.textContent = count++;
  10. // Update the saved state
  11. vscode.setState({ count });
  12. }, 100);

getState and setState are the preferred way to persist state, as they have much lower performance overhead than retainContextWhenHidden.

Serialization

By implementing a WebviewPanelSerializer, your webviews can be automatically restored when VS Code restarts. Serialization builds on getState and setState, and is only enabled if your extension registers a WebviewPanelSerializer for your webviews.

To make our coding cats persist across VS Code restarts, first add a onWebviewPanel activation event to the extension’s package.json:

  1. "activationEvents": [
  2. ...,
  3. "onWebviewPanel:catCoding"
  4. ]

This activation event ensures that our extension will be activated whenever VS Code needs to restore a webview with the viewType: catCoding.

Then, in our extension’s activate method, call registerWebviewPanelSerializer to register a new WebviewPanelSerializer. The WebviewPanelSerializer is responsible for restoring the contents of the webview from its persisted state. This state is the JSON blob that the webview contents set using setState.

  1. export function activate(context: vscode.ExtensionContext) {
  2. // Normal setup...
  3. // And make sure we register a serializer for our webview type
  4. vscode.window.registerWebviewPanelSerializer('catCoding', new CatCodingSerializer());
  5. }
  6. class CatCodingSerializer implements vscode.WebviewPanelSerializer {
  7. async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) {
  8. // `state` is the state persisted using `setState` inside the webview
  9. console.log(`Got state: ${state}`);
  10. // Restore the content of our webview.
  11. //
  12. // Make sure we hold on to the `webviewPanel` passed in here and
  13. // also restore any event listeners we need on it.
  14. webviewPanel.webview.html = getWebviewContent();
  15. }
  16. }

Now if you restart VS Code with a cat coding panel open, the panel will be automatically restored in the same editor position.

retainContextWhenHidden

For webviews with very complex UI or state that cannot be quickly saved and restored, you can instead use the retainContextWhenHidden option. This option makes a webview keep its content around but in a hidden state, even when the webview itself is no longer in the foreground.

Although Cat Coding can hardly be said to have complex state, let’s try enabling retainContextWhenHidden to see how the option changes a webview’s behavior:

  1. import * as vscode from 'vscode';
  2. export function activate(context: vscode.ExtensionContext) {
  3. context.subscriptions.push(
  4. vscode.commands.registerCommand('catCoding.start', () => {
  5. const panel = vscode.window.createWebviewPanel(
  6. 'catCoding',
  7. 'Cat Coding',
  8. vscode.ViewColumn.One,
  9. {
  10. enableScripts: true,
  11. retainContextWhenHidden: true
  12. }
  13. );
  14. panel.webview.html = getWebviewContent();
  15. })
  16. );
  17. }
  18. function getWebviewContent() {
  19. return `<!DOCTYPE html>
  20. <html lang="en">
  21. <head>
  22. <meta charset="UTF-8">
  23. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  24. <title>Cat Coding</title>
  25. </head>
  26. <body>
  27. <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
  28. <h1 id="lines-of-code-counter">0</h1>
  29. <script>
  30. const counter = document.getElementById('lines-of-code-counter');
  31. let count = 0;
  32. setInterval(() => {
  33. counter.textContent = count++;
  34. }, 100);
  35. </script>
  36. </body>
  37. </html>`;
  38. }

persistence retrain

Notice how the counter does not reset now when the webview is hidden and then restored. No extra code required! With retainContextWhenHidden, the webview acts similarly to a background tab in a web browser. Scripts and other dynamic content are suspended, but immediately resumed once the webview becomes visible again. You cannot send messages to a hidden webview, even when retainContextWhenHidden is enabled.

Although retainContextWhenHidden may be appealing, keep in mind that this has high memory overhead and should only be used when other persistence techniques will not work.

Next steps

If you’d like to learn more about VS Code extensibility, try these topics: