Table of Contents
调试Webview
你的插件必须用Webview吗?
创建WebviewPanel
1号坑:使用本地资源
2号坑:允许使用Javascript
3号坑:cookie和localstorage
4号坑:Webview内容被释放
消息通讯
官方Demo
Home Development Tools VSCode A brief discussion on how to use Webview in VSCode

A brief discussion on how to use Webview in VSCode

Jun 17, 2021 am 10:57 AM
vscode webview

本篇文章给大家介绍一下VSCode中Webview的使用方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

A brief discussion on how to use Webview in VSCode

其实VSCode也是基于electron框架的桌面软件,也就是说,你在VSCode里看到的所有的界面本就是网页。那在网页里再显示网页怎么做?相信你也想到了,就是iframe。【推荐学习:《vscode教程》】

调试Webview

VSCode命令面板中,输入Open Webview Developer Tools 后可以打开Webview的控制台

A brief discussion on how to use Webview in VSCode

果然是iframe~

你的插件必须用Webview吗?

官方英文文档地址:https://code.visualstudio.com/api/extension-guides/webview

VSCode官方团队希望插件开发者好好思考如下问题:

  • 这个功能真的需要在VS Code中使用吗?作为单独的应用程序或网站会更好吗?
  • 使用Webview是实现功能的唯一方法吗?您可以改用常规的VS Code API吗?

创建WebviewPanel

A brief discussion on how to use Webview in VSCode

const panel = vscode.window.createWebviewPanel(
  'webview',
  "测试webview",
  vscode.ViewColumn.One
);
panel.webview.html = `<html><body>你好,我是Webview</body></html>`
Copy after login

这样就能创建一个Webview,渲染html内容。

A brief discussion on how to use Webview in VSCode

看上去使用很简单对不对,但在实际使用Webview进行插件开发的过程中,还是遇到了不少坑的:

1号坑:使用本地资源

在VSCode中的Webview无法直接使用相对路径的本地资源。比如下面这段代码,我们引入了一个css,一个js,在body中有一张图片。

A brief discussion on how to use Webview in VSCode

直接这样写是无法加载到这些资源的

A brief discussion on how to use Webview in VSCode

A brief discussion on how to use Webview in VSCode

  • 解决方法1

通过一个特殊的协议头vscode-resource:资源文件绝对路径,为了不影响咱们正常进行网页开发,我们可以封装一个方法,从本地文件读取html内容,统一替换所有资源的路径后再赋值给panel.webview.html

function getWebViewContent(context, templatePath) {
	const resourcePath = path.join(context.extensionPath, templatePath);
	const dirPath = path.dirname(resourcePath);
	let html = fs.readFileSync(resourcePath, &#39;utf-8&#39;);
    html = html.replace(/(<link.+?href="|<script.+?|<img  src="/static/imghw/default1.png"  data-src="|<iframe.+?src="  class="lazy" .+?/g, (m, $1, $2) = alt="A brief discussion on how to use Webview in VSCode" > {
		if($2.indexOf("https://")<0)return $1 + vscode.Uri.file(path.resolve(dirPath, $2)).with({ scheme: &#39;vscode-resource&#39; }).toString() + &#39;"&#39;;
		else return $1 + $2+&#39;"&#39;;
	});
	return html;
}
Copy after login

这样我们在开发网页的时候就正常写相对路径就好了。

A brief discussion on how to use Webview in VSCode

A brief discussion on how to use Webview in VSCode

注意事项:如果你使用Vue或者其他前端框架来进行插件Webview的开发,就要注意资源的引入。以上封装的方法只对页面中hardcode的资源进行了替换。

  • 解决方法2

使用iframe引入本地路径html,不过VSCode的webview对iframe的限制也特别大,几乎就是除了显示网页,和node环境交互就别想了。

2号坑:允许使用Javascript

默认不支持Javascript

  • 解决方法

添加option,将enableScritps设置为true,它的默认是false。

A brief discussion on how to use Webview in VSCode

3号坑:cookie和localstorage

cookie和localStorage可以用,但是!!!

当VSCode重启后,就全都清空了,所以等于不能用。

  • 解决方法

调用VSCode的node环境来保存,这里需要让webview和VSCode插件环境进行通讯。

4号坑:Webview内容被释放

当Webview所在的tab pannel进入后台时(比如切到别的tab了),webview里的内容就会被清除,内存占用被释放。再次切回时会重新加载html内容。

  • 解决办法

启用retainContextWhenHidden

A brief discussion on how to use Webview in VSCode

消息通讯

1、插件发消息,Webview接收消息

  • 插件里的JS
panel.webview.postMessage({text: &#39;你好,我是插件&#39;});
Copy after login
  • Webview里的JS
window.addEventListener(&#39;message&#39;,function(e){
  console.log(e.data.text);
})
Copy after login

2、Webview发消息,插件接收消息

  • Webview里的JS
//初始化vscode插件api,没什么特别的功能,主要就是postMessage
var vscode = acquireVsCodeApi();

vscode.postMessage({
  text: &#39;你好,我是Webview&#39;
})
Copy after login
  • 插件里的JS
panel.webview.onDidReceiveMessage(function(data) {
  console.log(data.text);
});
Copy after login

比如前面提到的cookie和localstorage,就可以封装一下消息通讯,通过插件node环境来保存到本地

var vscode = acquireVsCodeApi();
function setLocalStorage(k,v){
  vscode.postMessage({
    command: &#39;setLocalStorage&#39;,
    key:k,
    value:v
  })
}
Copy after login
panel.webview.onDidReceiveMessage(function(data) {
  if(data.command == &#39;setLocalStorage&#39;){
    //使用lowdb
    lowdb.set(data.key,data.value).write();
  }
});
Copy after login

官方Demo

  • https://github.com/microsoft/vscode-extension-samples/tree/master/webview-sample
  • https://github.com/microsoft/vscode-extension-samples/tree/master/webview-view-sample

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of A brief discussion on how to use Webview in VSCode. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

How to define header files for vscode How to define header files for vscode Apr 15, 2025 pm 09:09 PM

How to define header files using Visual Studio Code? Create a header file and declare symbols in the header file using the .h or .hpp suffix name (such as classes, functions, variables) Compile the program using the #include directive to include the header file in the source file. The header file will be included and the declared symbols are available.

vscode terminal usage tutorial vscode terminal usage tutorial Apr 15, 2025 pm 10:09 PM

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Common commands for vscode terminal Common commands for vscode terminal Apr 15, 2025 pm 10:06 PM

Common commands for VS Code terminals include: Clear the terminal screen (clear), list the current directory file (ls), change the current working directory (cd), print the current working directory path (pwd), create a new directory (mkdir), delete empty directory (rmdir), create a new file (touch) delete a file or directory (rm), copy a file or directory (cp), move or rename a file or directory (mv) display file content (cat) view file content and scroll (less) view file content only scroll down (more) display the first few lines of the file (head)

How to solve the problem of vscode Chinese annotations becoming question marks How to solve the problem of vscode Chinese annotations becoming question marks Apr 15, 2025 pm 11:36 PM

How to solve the problem that Chinese comments in Visual Studio Code become question marks: Check the file encoding and make sure it is "UTF-8 without BOM". Change the font to a font that supports Chinese characters, such as "Song Style" or "Microsoft Yahei". Reinstall the font. Enable Unicode support. Upgrade VSCode, restart the computer, and recreate the source file.

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

vscode terminal command cannot be used vscode terminal command cannot be used Apr 15, 2025 pm 10:03 PM

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)

See all articles