A brief discussion on how to use Webview in VSCode
本篇文章给大家介绍一下VSCode中Webview的使用方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
其实VSCode
也是基于electron
框架的桌面软件,也就是说,你在VSCode
里看到的所有的界面本就是网页。那在网页里再显示网页怎么做?相信你也想到了,就是iframe
。【推荐学习:《vscode教程》】
调试Webview
在VSCode
命令面板中,输入Open Webview Developer Tools
后可以打开Webview
的控制台
果然是iframe~
你的插件必须用Webview吗?
官方英文文档地址:https://code.visualstudio.com/api/extension-guides/webview
VSCode官方团队希望插件开发者好好思考如下问题:
- 这个功能真的需要在VS Code中使用吗?作为单独的应用程序或网站会更好吗?
- 使用
Webview
是实现功能的唯一方法吗?您可以改用常规的VS Code API吗?
创建WebviewPanel
const panel = vscode.window.createWebviewPanel( 'webview', "测试webview", vscode.ViewColumn.One ); panel.webview.html = `<html><body>你好,我是Webview</body></html>`
这样就能创建一个Webview,渲染html内容。
看上去使用很简单对不对,但在实际使用Webview进行插件开发的过程中,还是遇到了不少坑的:
1号坑:使用本地资源
在VSCode中的Webview无法直接使用相对路径的本地资源。比如下面这段代码,我们引入了一个css,一个js,在body中有一张图片。
直接这样写是无法加载到这些资源的
- 解决方法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, 'utf-8'); 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: 'vscode-resource' }).toString() + '"'; else return $1 + $2+'"'; }); return html; }
这样我们在开发网页的时候就正常写相对路径就好了。
注意事项:如果你使用Vue或者其他前端框架来进行插件Webview的开发,就要注意资源的引入。以上封装的方法只对页面中
hardcode
的资源进行了替换。
- 解决方法2
使用iframe引入本地路径html,不过VSCode的webview对iframe的限制也特别大,几乎就是除了显示网页,和node环境交互就别想了。
2号坑:允许使用Javascript
默认不支持Javascript
- 解决方法
添加option
,将enableScritps
设置为true,它的默认是false。
3号坑:cookie和localstorage
cookie和localStorage可以用,但是!!!
当VSCode重启后,就全都清空了,所以等于不能用。
- 解决方法
调用VSCode的node环境来保存,这里需要让webview和VSCode插件环境进行通讯。
4号坑:Webview内容被释放
当Webview所在的tab pannel进入后台时(比如切到别的tab了),webview里的内容就会被清除,内存占用被释放。再次切回时会重新加载html内容。
- 解决办法
启用retainContextWhenHidden
消息通讯
1、插件发消息,Webview接收消息
- 插件里的JS
panel.webview.postMessage({text: '你好,我是插件'});
- Webview里的JS
window.addEventListener('message',function(e){ console.log(e.data.text); })
2、Webview发消息,插件接收消息
- Webview里的JS
//初始化vscode插件api,没什么特别的功能,主要就是postMessage var vscode = acquireVsCodeApi(); vscode.postMessage({ text: '你好,我是Webview' })
- 插件里的JS
panel.webview.onDidReceiveMessage(function(data) { console.log(data.text); });
比如前面提到的cookie和localstorage,就可以封装一下消息通讯,通过插件node环境来保存到本地
var vscode = acquireVsCodeApi(); function setLocalStorage(k,v){ vscode.postMessage({ command: 'setLocalStorage', key:k, value:v }) }
panel.webview.onDidReceiveMessage(function(data) { if(data.command == 'setLocalStorage'){ //使用lowdb lowdb.set(data.key,data.value).write(); } });
官方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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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 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.

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 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 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.

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 →

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)
