【VS Code插件开发】Webview面板(三)

🐱 个人主页:不叫猫先生 ,公众号:前端舵手

🙋‍♂️ 作者简介:前端领域优质作者、阿里云专家博主,共同学习共同进步,一起加油呀!

📢 资料领取:前端进阶资料可以找我免费领取

🔥 摸鱼学习交流:我们的宗旨是在「工作中摸鱼,摸鱼中进步」,期待大佬一起来摸鱼(文末有我wx或者私信)

目录

前言

Webview API 允许扩展在 VS Code 中创建完全可自定义的视图。例如,内置的 Markdown 扩展使用 webview 来渲染 Markdown 预览。Webview 还可以用于构建超出 VS Code 原生 API 支持范围的复杂用户界面。在视图中,会将 Webview 视为iframe。

Webview官方文档讲解
Webview官方案例

一、createWebviewPanel

vscode.window.createWebviewPanel 是 VS Code 扩展 API 中的一个方法,用于创建和管理 Webview 面板。Webview 面板允许您在 VS Code 的用户界面中嵌入一个基于 Web 技术的交互式内容。具体用法如下:

javascript 复制代码
vscode.window.createWebviewPanel(
    viewType: string,        // 唯一的视图类型标识符,用于在插件中识别不同的 Webview 面板
    title: string,           // 面板的标题
    viewColumn: vscode.ViewColumn, // 面板要显示在哪一列
    options?: vscode.WebviewPanelOptions & { enableScripts?: boolean } // 配置选项
): vscode.WebviewPanel;

参数详解:

  • viewType:唯一的视图类型标识符,用于在插件中区分不同的 Webview 面板。可以在插件的不同部分使用这个标识符来识别和操作特定的面板
  • title:面板的标题,显示在面板的顶部
  • viewColumn:是一个枚举类型,表示面板显示在编辑器中的第几列,枚举包括下面几个选项
    • ViewColumn.One:在第一列显示面板
    • ViewColumn.Two:在第二列显示面板
    • ViewColumn.Three:在第三列显示面板
    • ViewColumn.Active:在当前活动的列显示面板
    • ViewColumn.Beside:在当前列的旁边显示面板
  • options:可选的配置选项,设置Webview面板的各种属性,其中
    • enableScripts:是一个布尔值,表示是否在Webview中运行JS

二、Webview案例

使用registerCommand注册一个启动面板的命令(demoPlugin.start),然后创建一个面板。案例实现了创建一个带有猫的图片面板:面板的唯一标识catCoding,面板的标题为Cat Coding ,面板展示在编辑器中的第一列,配置选项为一个空对象。注意我们这里设置的webview.html会被视为iframe

  • 声明图片
javascript 复制代码
const cats = {
	'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
	'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};
  • 注册命令以及创建面板
javascript 复制代码
		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; 重新定义面板的标题
			panel.webview.html = getWebviewContent(cat);
})			
  • 面板具体的Html
javascript 复制代码
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>
	  /* 根据主题更改文本颜色 */
	  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中,需要在contributes中的commands进行配置。
javascript 复制代码
"contributes": {
   "commands": [
     {
        "command": "demoPlugin.start",
        "title": "Start new cat coding session",
        "category": "Cat Coding"
      }
   ]
}   
  • 展示
    最后我们就可以cmd/ctrl+shift+p在命令列表中选择配置的Cat Coding:Start new cat coding session命令。

面板动态切换

我们设置一秒对面板的内容和标题进行切换。这里是用定时器,1s切换面板的内容,并且在面板关闭时(使用onDidDispose监听)清除更新内容的定时器,避免内存泄漏。getWebviewConten方法还是上面的不变。

其中解释一下onDidDispose,该方法用于监听 Webview 面板被关闭。

语法:

javascript 复制代码
currentPanel.onDidDispose(() => { 
// 这里是面板关闭要执行的逻辑 
}, undefined, context.subscriptions)

参数详解:

  • 第一个参数是一个函数,表示面板被关闭时要执行的逻辑。在这个例子中,函数体内的代码将 currentPanel 设置为 undefined,以表示面板已经被关闭。
  • 第二个参数是一个可选的 this 上下文,这里设置为 undefined。
  • 第三个参数 context.subscriptions 是一个数组,通常包含了注册的事件和资源的句柄。在扩展被停用时,VS Code 将会自动清理这些资源,避免内存泄漏。
javascript 复制代码
		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();
		})

最终结果如下所示:

三、Theming webview content(主题化视图内容)

Webview 可以使用 CSS 根据 VS Code 的当前主题更改其外观。VS Code 将主题分为三类,并向body元素添加一个特殊的类来指示当前主题:

  • vscode-light:浅色主题
  • vscode-dark:黑暗主题
  • vscode-high-contrast:高对比度主题

在Web.html中添加主题样式,如下

javascript 复制代码
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>
	  /* 根据主题更改文本颜色 */
	  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

  • body.vscode-dark

  • body.vscode-high-contrast

相关推荐
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
bobostudio19952 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
黄尚圈圈3 小时前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
hallo1284 小时前
vscode环境迁移
ide·vscode·编辑器
浮华似水4 小时前
简洁之道 - React Hook Form
前端
家有狸花4 小时前
VSCODE驯服日记(三):配置C++环境
c++·ide·vscode
正小安6 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
yufei-coder6 小时前
掌握 C# 中的 LINQ(语言集成查询)
windows·vscode·c#·visual studio
_.Switch7 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光7 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js