Skip to main content
The Webview API allows extensions to create fully customizable views within VS Code using HTML, CSS, and JavaScript. Webviews can display rich content, interactive UI, and communicate bidirectionally with your extension.

Overview

Webviews enable:
  • Custom editors and visualizations
  • Rich previews (Markdown, SVG, etc.)
  • Interactive dashboards and forms
  • Embedded web applications
  • Custom data viewers
Webviews are powerful but come with security implications. Always sanitize untrusted content and set proper Content Security Policies.

Creating Webview Panels

Basic Webview Panel

Create a webview panel with window.createWebviewPanel():

Webview Interface

The Webview interface provides methods for communication and content management:

Webview Options

Configure webview behavior with WebviewOptions:
Enable JavaScript execution in the webview. Defaults to false.
List of URI roots from which the webview can load local resources. Restricts which files can be accessed.
Enable the find widget in the webview panel. Defaults to false.
Keep the webview’s context (iframe) around even when hidden. Has high memory overhead. Defaults to false.

Loading Local Resources

Using asWebviewUri()

Convert local file URIs to webview-safe URIs:

Resource Root Configuration

Message Passing

Webviews communicate with extensions through message passing.

Extension to Webview

Send messages from extension to webview:

Webview to Extension

Send messages from webview to extension:

Complete Example: Interactive Counter

Content Security Policy

Always set a Content Security Policy to protect against malicious content:

CSP Directives

Block all content by default. Explicitly allow what you need.
Allow images from webview resources and HTTPS URLs.
Allow scripts only from your extension. Never use ‘unsafe-inline’ or ‘unsafe-eval’.
Allow styles from your extension. ‘unsafe-inline’ is needed for inline styles.

Webview State Persistence

Using getState() and setState()

Persist webview state within a session:

Serialization Across Sessions

Use WebviewPanelSerializer to restore webviews across VS Code restarts:

Webview Views

Create webviews in the sidebar, panel, or other view containers:

Registering a Webview View

Package.json Contribution

Custom Text Editors

Create custom editors for specific file types:

Best Practices

Always set a strict CSP to prevent XSS attacks.
Never directly inject user-provided content into HTML.
Respect user theme by using VS Code’s CSS variables.
Clean up event listeners when webview is disposed.
Only use retainContextWhenHidden when absolutely necessary due to high memory cost.

Text Editor API

Work with text documents and editors

Workspace API

Access workspace files and settings

Commands API

Register commands to open webviews