Overview
Webviews enable:- Custom editors and visualizations
- Rich previews (Markdown, SVG, etc.)
- Interactive dashboards and forms
- Embedded web applications
- Custom data viewers
Creating Webview Panels
Basic Webview Panel
Create a webview panel withwindow.createWebviewPanel():
Webview Interface
TheWebview interface provides methods for communication and content management:
Webview Interface
Webview Interface
Webview Options
Configure webview behavior withWebviewOptions:
enableScripts
enableScripts
Enable JavaScript execution in the webview. Defaults to
false.localResourceRoots
localResourceRoots
List of URI roots from which the webview can load local resources. Restricts which files can be accessed.
enableFindWidget
enableFindWidget
Enable the find widget in the webview panel. 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
default-src 'none'
default-src 'none'
Block all content by default. Explicitly allow what you need.
img-src
img-src
Allow images from webview resources and HTTPS URLs.
script-src
script-src
Allow scripts only from your extension. Never use ‘unsafe-inline’ or ‘unsafe-eval’.
style-src
style-src
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
UseWebviewPanelSerializer 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
Use Content Security Policy
Use Content Security Policy
Always set a strict CSP to prevent XSS attacks.
Sanitize User Input
Sanitize User Input
Never directly inject user-provided content into HTML.
Use VS Code CSS Variables
Use VS Code CSS Variables
Respect user theme by using VS Code’s CSS variables.
Dispose Properly
Dispose Properly
Clean up event listeners when webview is disposed.
Related APIs
Text Editor API
Work with text documents and editors
Workspace API
Access workspace files and settings
Commands API
Register commands to open webviews