[VS Code Plugin Development] Webview Panel

Time:2023-10-23

VS Code plug-in development series of columns

writings
Primer (I)
General function (II)
WebView Panel (III)
Message communications (IV)
Status bar (v)
Customized sidebars, views (vi)
Common customization commands (VII)

Webview Panel

The Webview API allows extensions to create fully customizable views in VS Code. For example, the built-in Markdown extension uses webview to render Markdown previews. webview can also be used to build complex user interfaces that are beyond the scope of VS Code’s native API support. A webview is treated as an iframe in the view. Webview Official Documentation Webview Official Case

I. createWebviewPanel

vscode.window.createWebviewPanel is a method in the VS Code Extension API for creating and managing Webview panels, which allow you to embed an interactive Web technology-based content in the VS Code user interface. The usage is described below:
vscode.window.createWebviewPanel(
    viewType: string, // unique view type identifier, used to recognize different Webview panels in the plugin
    title: string, // Title of the panel
    viewColumn: vscode.ViewColumn, // the column in which the panel is to be displayed
    options? : vscode.WebviewPanelOptions & { enableScripts? : boolean} // Configuration options
): vscode.WebviewPanel;
Parameter details:
  • viewType: unique view type identifier used to distinguish between different Webview panels in the plugin. This identifier can be used in different parts of the plugin to identify and manipulate specific panels.
  • title: title of the panel, displayed at the top of the panel
  • viewColumn: is an enumeration type indicating the column in the editor where the panel is displayed, the enumeration consists of the following options
    • ViewColumn.One: show panel in first column
    • ViewColumn.Two: show the panel in the second column
    • ViewColumn.Three: show panel in third column
    • ViewColumn.Active: show the panel in the currently active column
    • ViewColumn.Beside: Show panel next to current column
  • options: optional configuration options that set various properties of the Webview panel, including
    • enableScripts: is a boolean value indicating whether to run JS in the webview or not

Second, Webview case

utilizationregisterCommandRegister a command to launch the panel (demoPlugin.start) and then create a panel. The case implementation creates a panel with a picture of a cat: the panel’s unique identifiercatCodingThe panel is titledCat Coding , the panel is displayed in the first column in the editor with the configuration option as an empty object. Notice that we set thewebview.htmlwould be considerediframe
  • Statement Pictures
const cats = {
	'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
	'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};
  • Registering commands and creating panels
vscode.commands.registerCommand('demoPlugin.start', () => {
			// Create and show a new webview
			const panel = vscode.window.createWebviewPanel(
				'catCoding', // Identifies the type of the webview. Used internally
				'Cat Coding', // Title of the panel displayed to the user
				vscode.ViewColumn.One, // Editor column to show the new webview panel in.
				{} // Webview options. More on these later.
			);
			const cat = "Coding Cat";
			//panel.title = cat; redefine the title of the panel
			panel.webview.html = getWebviewContent(cat);
})
  • Panel Specific Html
function getWebviewContent(cat: keyof typeof cats) {
	return `<!DOCTYPE html>
  <html lang="en">
  <head>
	  <meta charset="UTF-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	  <title>Cat Coding</title>
	  <style>
	  /* Change text color according to theme */
	  body.vscode-light {
		color: #ff0;
	  }

	  body.vscode-dark {
		color: white;
	  }

	  body.vscode-high-contrast {
		color: red;
	  }
	  </style>
  </head>
  <body>
	  <img src="${cats[cat]}" width="300" />
  </body>
  </html>`;
}
  • package.json, it is necessary to add a new file to thecontributeshit the nail on the headcommandsPerform the configuration.
"contributes": {
   "commands": [
     {
        "command": "demoPlugin.start",
        "title": "Start new cat coding session",
        "category": "Cat Coding"
      }
   ]
}
  • showcase Finally we’ll be able tocmd/ctrl+shift+pIn the command list, select the configuredCat Coding:Start new cat coding sessionInstructions. [VS Code Plugin Development] Webview Panel [VS Code Plugin Development] Webview Panel

Panel dynamic switching

We set one second to toggle the panel’s content and title. Here it’s using a timer, 1s to toggle the panel’s content, and when the panel is closed (using theonDidDispose(Listen) Clear the timer for updating the content to avoid memory leaks.getWebviewContenThe method remains the same as above. Which explainsonDidDisposeThis method is used to listen for the Webview panel to be closed. Grammar:
currentPanel.onDidDispose(() => { 
// Here is the logic to be executed when the panel is closed 
}, undefined, context.subscriptions)
Parameter details:
  • The first argument is a function that indicates the logic to be executed when the panel is closed. In this example, the code inside the function sets currentPanel to undefined to indicate that the panel has been closed.
  • The second argument is an optional this context, which is set to undefined.
  • The third parameter, context.subscriptions, is an array that usually contains handles to registered events and resources. VS Code will automatically clean up these resources when the extension is deactivated to avoid memory leaks.
vscode.commands.registerCommand('demoPlugin.start', () => {
			// Create and show a new webview
			const panel = vscode.window.createWebviewPanel(
				'catCoding', // Identifies the type of the webview. Used internally
				'Cat Coding', // Title of the panel displayed to the user
				vscode.ViewColumn.One, // Editor column to show the new webview panel in.
				{} // Webview options. More on these later.
			);
			panel.webview.html = getWebviewContent(cat);
			const cat = "Coding Cat";
			let iteration = 0;
			const updateWebview = () => {
				const cat = iteration++ % 2 ? 'Compiling Cat' : 'Coding Cat';
				panel.title = cat;
				panel.webview.html = getWebviewContent(cat);
			};
			// And schedule updates to the content every second
			const interval = setInterval(updateWebview, 1000);
			panel.onDidDispose(
				() => {
					// When the panel is closed, cancel any future updates to the webview content
					clearInterval(interval);
				},
				null,
				context.subscriptions
			);
			// Set initial content
			updateWebview();
		})
The final result is shown below: [VS Code Plugin Development] Webview Panel

III. Thematic webview content

Webviews can use CSS to change their appearance based on the current theme in VS Code, which categorizes themes into three classes and adds a special class to the body element to indicate the current theme:
  • vscode-light: light color theme
  • vscode-dark: dark theme
  • vscode-high-contrast: high contrast theme
Add the theme style in Web.html as follows
function getWebviewContent(cat: keyof typeof cats) {
	return `<!DOCTYPE html>
  <html lang="en">
  <head>
	  <meta charset="UTF-8">
	  <meta name="viewport" content="width=device-width, initial-scale=1.0">
	  <title>Cat Coding</title>
	  <style>
	  /* Change text color according to theme */
	  body.vscode-light {
		color: blue;
	  }
  
	  body.vscode-dark {
		color: green;
	  }
  
	  body.vscode-high-contrast {
		color: yellow;
	  }
	  </style>
  </head>
  <body>
	  <img src="${cats[cat]}" width="300" />
  </body>
  </html>`;
}
  • body.vscode-light [VS Code Plugin Development] Webview Panel
  • body.vscode-dark [VS Code Plugin Development] Webview Panel
  • body.vscode-high-contrast [VS Code Plugin Development] Webview Panel

Recommended VS Code plug-ins for “WeChat Reader”.

Plugin Marketplace Search: WeChat Reading Note: This plugin can only read the books in my bookshelf, you can’t read the books that are not added to the bookshelf, so you can only read them by other means such as PC or cell phone after adding the books to the bookshelf first. [VS Code Plugin Development] Webview Panel

Recommended Today

uniapp and applet set tabBar and show and hide tabBar

(1) Set the tabBar: uni.setTabberItem({}); wx.setTabberItem({}); indexnumberisWhich item of the tabBar, counting from the left, is indexed from 0.textstringnoButton text on tabiconPathstringnoImage PathselectedIconPathstringnoImage path when selectedpagePathstringnoPage absolute pathvisiblebooleannotab Whether to display uni.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) wx.setTabBarItem({ index: 0, text: ‘text’, iconPath: ‘/path/to/iconPath’, selectedIconPath: ‘/path/to/selectedIconPath’, pagePath: ‘pages/home/home’ }) […]