【vscode插件开发】 (三) webview api使用

已被阅读 1239 次 | 文章分类:日常随笔 | 2022-04-09 23:03

通俗点说:webview即web视图,使用webview api 你可以在vscode中打开一个完整的的html,该视图就跟嵌入页面一样,用html语法就可以渲染;而且还可以调用一些vscode的原生api做一些复杂的交互; 跟着官网实现几个小例子,后续可以自己实现一些具体复杂功能

1 新建一个扩展文件

本节不用默认的extension.js,在src目录下创建一个extension_webview.ts文件;

然后修改package.json中主文件为该文件

                                            
"main": "./out/extension_webview.js",
                                            
                                        

2 实现一个webview

实现一个空webview,也就是没有任何内容的webview;

(1)在extension_webview.ts中添加如下代码;

                                            
/**
	 * 1 webview1  
	 * 一个空白的webview
	 */
	context.subscriptions.push(
		vscode.commands.registerCommand('geojsonviewer.webview1', () => {
		  // 创建并显示一个新的webview
		  const panel = vscode.window.createWebviewPanel(
			'Test', // 标识webview的类型
			'webview1', // 展示给用户的面板的标题
			vscode.ViewColumn.One, // 显示webview面板以编辑器新列的方式.
			{} // webview其他的选项
		  );
		})
	  );
                                            
                                        

基本思路跟我们之前写过的基本命令添加方式一样:

                                            
第一步:创建一个命令;

第二步:在命令回调函数中定义主体;可以是弹出窗口,可以是webview等等

第三步:将命令添加到订阅数组;
                                            
                                        

(2)在package.json中添加启动命令

有两处位置需要添加

第一:在activationEvents中添加

                                            
"activationEvents": [
		"onCommand:geojsonviewer.webview1"
	],
                                            
                                        

第二:在command中添加如下

                                            
"contributes": {
		"commands": [
			{
				"command": "geojsonviewer.webview1",
				"title": "webview1",
				"category": "webview1"
			}
		]
	}
                                            
                                        

(3)到此就可以运行了;F5运行;新打开一个扩展宿主环境窗口

ctrl+shift+p打开命令输入框,输入webview1,然后点击

/net/upload/image/20220409/6215d093f56f487680c65858b37c5dda.png

新打开一个webview1的面板,如下

/net/upload/image/20220409/21438730472645faa3557db906a9d677.png

3 给webview添加内容

webview的内容,通过返回html内容即可;内容定义的方式跟html一样,没有任何区别; 通过panel.webview.html 设置webview的内容;如下

                                            
/**
	 * 2 webview2  
	 * 有内容的webview
	 */
	  context.subscriptions.push(
		vscode.commands.registerCommand('geojsonviewer.webview2', () => {
		  // 创建并显示一个新的webview
		  const panel = vscode.window.createWebviewPanel(
			'Test', // 标识webview的类型
			'webview2', // 展示给用户的面板的标题
			vscode.ViewColumn.One, // 显示webview面板以编辑器新列的方式.
			{} // webview其他的选项
		  );
		  panel.webview.html = getWebviewContent();
		  function getWebviewContent() {
			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>
		  </head>
		  <body>
			  <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />
		  </body>
		  </html>`;
		  }
		})
	  );
                                            
                                        

上面添加一个gif图片;这里直接借鉴官网的实例图片。

同样在package.json中添加启动命令;F5运行查看效果

/net/upload/image/20220409/9dc7b3a0b72a49f7a3e3c836efa84b43.png

4 给webview动态传值更新webview的内容

这里引用官方的例子

                                            
/**
	 * 3 webview3
	 * 可以给webview传值,动态改变内容的webview
	 */
	   context.subscriptions.push(
		vscode.commands.registerCommand('geojsonviewer.webview3', () => {
			const cats = {
				'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
				'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
			  };
		  // 创建并显示一个新的webview
		  const panel = vscode.window.createWebviewPanel(
			'Test', // 标识webview的类型
			'webview2', // 展示给用户的面板的标题
			vscode.ViewColumn.One, // 显示webview面板以编辑器新列的方式.
			{} // webview其他的选项
		  );
 
		  let iteration = 0;
		  const updateWebview = () => {
			const cat = iteration++ % 2 ? 'Compiling Cat' : 'Coding Cat';
			panel.title = cat;
			panel.webview.html = getWebviewContent(cat);
		  };
	
		  // Set initial content
		  updateWebview();
		  setInterval(updateWebview, 1000);
		  
		  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>
		  </head>
		  <body>
		  	<img src="${cats[cat]}" width="300" />
		  </body>
		  </html>`;
		  }
 
		})
	  );
                                            
                                        
                                            
上面主要是通过setInterval函数间隔更新视图;其中需要注意getWebviewContent函数在接受形参的时候使用keyof typeof cats的方式;这意味着形参类型只能属于cats对象所有参数里;参数名没有的话就会报错
                                            
                                        

在package.json中增加启动命令;F5运行

/net/upload/image/20220409/5816c9d5d13c441c8e218c69616da99a.gif

5 加载本地资源

上面的例子,gif图片是在线地址;如果要加载本地资源,该如何将地址传给webview呢;我们直接在return 返回的html里面设置本地资源地址是无效的;这里我们需要借助两个api

                                            
第一个:vscode.Uri.file,通过该api获取资源的所在磁盘地址

第二个: panel.webview.asWebviewUri,将其转换为vscode-resource地址;然后将该地址传给html即可。
                                            
                                        

代码如下:

                                            
/**
	   * 4 webview4 
	   * 从本地加载gif图像
	   */
	   context.subscriptions.push(
		vscode.commands.registerCommand('geojsonviewer.webview4', () => {
		  const panel = vscode.window.createWebviewPanel(
			'catCoding',
			'Cat Coding',
			vscode.ViewColumn.One,
			{}
		  );
	
		  // Get path to resource on disk
		  const onDiskPath = vscode.Uri.file(
			path.join(context.extensionPath, 'media', 'cat.webp')
		  );
			console.log("context.extensionPath",context.extensionPath);
		  // And get the special URI to use with the webview
		  const catGifSrc = panel.webview.asWebviewUri(onDiskPath)+"";
		  console.log("catGifSrc",catGifSrc);
		  panel.webview.html = getWebviewContent(catGifSrc);
		  function getWebviewContent(_src:string) {
			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>
		  </head>
		  <body>
		  	<img src="${_src}" width="300" />
		  </body>
		  </html>`;
		  }
 
		})
	   )
                                            
                                        
                                            
其中path.join(context.extensionPath, 'media', 'cat.webp') ;“media”是资源的目录,“cat.webp”是资源名称;
                                            
                                        

/net/upload/image/20220409/cc847121ca424925a99a56afd41b0a8b.png

最后增加启动命令运行即可;

                                            
"activationEvents": [
		"onCommand:geojsonviewer.webview1",
		"onCommand:geojsonviewer.webview2",
		"onCommand:geojsonviewer.webview3",
		"onCommand:geojsonviewer.webview4"
	],
	"main": "./out/extension_webview.js",  
	
	"contributes": {
		"commands": [
			{
				"command": "geojsonviewer.webview1",
				"title": "webview1",
				"category": "webview1"
			},
			{
				"command": "geojsonviewer.webview2",
				"title": "webview2",
				"category": "webview2"
			},
			{
				"command": "geojsonviewer.webview3",
				"title": "webview3",
				"category": "webview3"
			},
			{
				"command": "geojsonviewer.webview4",
				"title": "webview4",
				"category": "webview4"
			}
		]
	},
                                            
                                        

QQ:3410192267 | 技术支持 微信:popstarqqsmall

Copyright ©2017 xiaobaigis.com . 版权所有 鲁ICP备17027716号