初识vscode插件开发(四)-webview api

55 篇文章 4 订阅
23 篇文章 0 订阅

通俗点说: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,然后点击

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

 

 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运行查看效果

 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运行

 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”是资源名称;

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

	"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"
			}
		]
	},

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 VS Code 插件开发中,如果需要在 Webview 中使用 `child_process.fork()` 方法创建多进程,需要进行如下操作: 1. 在插件的 `package.json` 文件中配置 `"browser"` 字段,将需要使用的模块路径映射到实际的模块路径上。例如: ```json { "name": "my-extension", "version": "1.0.0", "main": "extension.js", "browser": { "child_process": "./node_modules/electron/dist/electron.js" } } ``` 在这个例子中,我们将 `child_process` 模块的路径映射到了 Electron 的路径上。 2. 在 Webview 中使用 `require()` 方法加载模块时,需要使用 `nodeIntegration: true` 选项来启用 Node.js 的集成。例如: ```javascript const vscode = acquireVsCodeApi(); const { fork } = require('child_process').remote; const child = fork('fileProcessor.js'); child.on('message', (result) => { console.log(`Processed file: ${result}`); }); child.send('file.txt'); ``` 在这个例子中,我们使用 `require()` 方法加载 `child_process` 模块,并通过 `remote` 对象使用 `fork()` 方法创建子进程。然后,我们通过 `send()` 方法向子进程发送文件名参数,并通过 `message` 事件监听子进程的输出结果。 需要注意的是,在使用 Webview 中的多进程时,需要考虑安全问题。Webview 中的代码可以访问用户计算机上的文件系统和网络资源,并可能执行恶意代码。因此,需要对 Webview 中的代码进行严格的输入验证和代码审查,以确保插件的安全性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨大大28

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值