webview API允许扩展在Visual Studio Code中创建完全可自定义的视图。例如,内置的 Markdown 扩展使用 Web 视图来呈现 Markdown 预览。
Web 视图自由且强大、可用于构建超出 VS Code 本机 API 支持的复杂用户界面。
github示例项目
github示例项目2
使用注意
web视图消耗资源巨大,若能通过vscode本机Api实现功能,则尽可能不要采用此法
跟随示例来学习web视图
web视图的基础知识
创建一个命令来开我们的web视图
再package.json中的 contributes字段下,注册一个命令,如下图:
其中catCoding.start是我们实际关联的命令。下面两个字段是命令的名字和描述
创建web视图本体
在extension.ts中写入以下内容
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.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.
);
})
);
}
这段代码额意思是注册一个名为catCoing.start的命令。该命令调用vscode.window.createWebviewPanel方法创建一个web视图。其第二个参数Cat Coding是标签页的名称,第三个参数表示web视图展示在哪一栏的工作区中
至此我们创建了一个新的web视图,它有标题,不过没有内容
为新的web视图注入html内容
依然是在extension.ts文件中,改为一下内容:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
// Create and show panel
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{}
);
// And set its HTML content
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>`;
}
如上所示,html的内容添加在webViewPanel的webview.html属性当中。webview.html是一个完整的html文件的内容,主语语法哦!
我们在这里向html中添加了一张gif图:一个敲键盘的猫猫
内容修改:可以做更多
我们可以多写一些东西,使得整个页面内容更加灵活
import * as vscode from 'vscode';
const cats = {
'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{}
);
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();
// And schedule updates to the content every second
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>`;
}
上面的代码新增的内容是:每秒调用切换一次猫猫的图片
通过panel.title来修改panel的标题
通过panel.webview.html来修改页面的内容
生命周期panel.onDidDispose
web视图有自己的生命周期api。
panel.dispose
方法用于关闭web视图
panel.onDidDispose
用于在视图关闭时调用,使用方法如下:
panel.onDidDispose(
() => {
// When the panel is closed, cancel any future updates to the webview content
clearInterval(interval);
},
null,
context.subscriptions
);
读取当前panel是否为可见状态
当选中其他标签页时,咱们的web视图的panel.visible
将会变为false
同一时刻相同web视图只允许存在一个
当前我们可以同时又多个coding Cat的web视图,这在很多时候显然是不符合用户需求的,我们可以将其改成同一时刻相同web视图只允许存在一个
import * as vscode from 'vscode';
const cats = {
'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif'
};
export function activate(context: vscode.ExtensionContext) {
// Track currently webview panel
let currentPanel: vscode.WebviewPanel | undefined = undefined;
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
const columnToShowIn = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: undefined;
if (currentPanel) {
// If we already have a panel, show it in the target column
currentPanel.reveal(columnToShowIn);
} else {
// Otherwise, create a new panel
currentPanel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{}
);
currentPanel.webview.html = getWebviewContent('Coding Cat');
// Reset when the current panel is closed
currentPanel.onDidDispose(
() => {
currentPanel = undefined;
},
null,
context.subscriptions
);
}
})
);
}
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>`;
}
这里用到的一个zpi是panel.reveal()
,该方法用于将视图重新显示到当前的工作区
这里的columnToShowIn
就是获取的当前的工作区在哪一栏
生命周期onDidChangeViewState
前面我们了解了panel.onDidDispose
,下面来了解一个新的生命周期函数onDidChangeViewState
每当 Web 视图的可见性更改或将 Web 视图移动到新列时,都会触发该事件。我们的扩展可以使用此事件根据 Web 视图显示在哪一列中来更改猫:onDidChangeViewState
import * as vscode from 'vscode';
const cats = {
'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{}
);
panel.webview.html = getWebviewContent('Coding Cat');
// Update contents based on view state changes
panel.onDidChangeViewState(
e => {
const panel = e.webviewPanel;
switch (panel.viewColumn) {
case vscode.ViewColumn.One:
updateWebviewForCat(panel, 'Coding Cat');
return;
case vscode.ViewColumn.Two:
updateWebviewForCat(panel, 'Compiling Cat');
return;
case vscode.ViewColumn.Three:
updateWebviewForCat(panel, 'Testing Cat');
return;
}
},
null,
context.subscriptions
);
})
);
}
function updateWebviewForCat(panel: vscode.WebviewPanel, catName: keyof typeof cats) {
panel.title = catName;
panel.webview.html = getWebviewContent(catName);
}
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>`;
}
加载本地内容
如果你注意看了我们的代码就会发现,我们的猫猫的gif路径是用的线上路径
为什么不在文件夹中直接放几张图呢?
因为Web 视图在无法直接访问本地资源的隔离上下文中运行。
这样做是出于安全原因。
同时这意味着,为了从扩展加载图像、样式表和其他资源,或从用户的当前工作区加载任何内容,必须使用panel.webview.asWebviewUri
函数将 localURI 转换为 VS Code 可用于加载本地资源子集的特殊 URI。
import * as vscode from 'vscode';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
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.gif')
);
// And get the special URI to use with the webview
const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
panel.webview.html = getWebviewContent(catGifSrc);
})
);
}
function getWebviewContent(cat: any) {
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="${cat}" width="300" />
</body>
</html>`;
}
上面的代码中onDiskPath为gif的localURI,注意其写法:
path.join(context.extensionPath, 'media', 'cat.gif')
拼接路径
vscode.Uri.file
获取localURI
亲测这样写也是一样的:
const onDiskPath = vscode.Uri.file(
"/g:/vscode-extension-samples-main/vscode-extension-samples-main/webview-sample/media/cat.gif"
);
再用panel.webview.asWebviewUri
转换成vscode可识别的特殊URI,并从该位置加载gif图
注意:
默认情况下,Web 视图只能访问以下位置的资源:
- 在扩展的安装目录中。
- 在用户当前处于活动状态的工作区中。
使用WebviewOptions.localResourceRoots则能够允许访问其他本地资源。
还可以始终使用数据 URI 直接在 Web 视图中嵌入资源。
控制本地资源访问:WebviewOptions.localResourceRoots
说到WebviewOptions.localResourceRoots我们需要回头看看我们创建web视图时的初始化方法:vscode.window.createWebviewPanel()当时我们介绍了前三个参数的含义,那么第四个参数为什么是个空对象呢?
其实第四个参数就是我们这里说的WebviewOptions.localResourceRoots,它控制我们的视图可以访问的本地资源,空对象表示使用默认值,也就是上述默认情况下可以访问的扩展的安装目录中和用户当前处于活动状态的工作区中。
如果按照下述设置,则表示完全隔离本地环境,不能访问任何本地资源:
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{
localResourceRoots: []
}
);
可以通过设置对象中localResourceRoots的值来使视图对某些本地资源拥有访问权限。
vscode.commands.registerCommand('catCoding.start', () => {
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{
enableScripts: true,
localResourceRoots: [
vscode.Uri.file(path.join(context.extensionPath, "media")),
vscode.Uri.file(vscode.env.appRoot)
]
}
下片段代码段表示只从扩展中的目录加载资源
{
localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath, 'media'))]
}
今天先到这里
import * as vscode from 'vscode';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
const panel = vscode.window.createWebviewPanel(
'catCoding',
'Cat Coding',
vscode.ViewColumn.One,
{
localResourceRoots: [
vscode.Uri.file(path.join(context.extensionPath, "html")),
vscode.Uri.file(vscode.env.appRoot)
]
}
);
// Get path to resource on disk
const onDiskPath = vscode.Uri.file(
path.join(context.extensionPath, 'media', 'cat.gif')
);
console.log(context.extensionPath,path,path.join(context.extensionPath, 'media', 'cat.gif'),onDiskPath)
// And get the special URI to use with the webview
const catGifSrc = panel.webview.asWebviewUri(onDiskPath);
panel.webview.html = getWebviewContent("/g:/vscode-extension-samples-main/vscode-extension-samples-main/webview-sample/media/cat.gif");
})
);
}
function getWebviewContent(cat: any) {
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="${cat}" width="300" />
</body>
</html>`;
}
web视图的主题样式
web视图作为vscode的一部分,我们是可以让其根据vscode的皮肤来自动切换样式颜色的
VS Code 将主题分为三个类别,并向元素添加一个特殊类以指示当前主题:body
- vscode-light 亮主题。
- vscode-dark 暗主题。
- vscode-high-contrast 高对比度主题。
下面我们用一个现实例子来说明:
①我们在extension.ts的html里面,将body标签内容改成:
<body>
<img src="${catGifPath}" width="300" />
<h1>我不应该变色</h1>
<h1 id="lines-of-code-counter">0</h1>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
②在media/vscode.css里面使用我们上面提到的技巧,根据vscode的主题,来设置id为lines-of-code-counter
的标签的颜色。
body.vscode-light #lines-of-code-counter {
color: rgb(230, 8, 174);
}
body.vscode-dark #lines-of-code-counter{
color: rgb(239, 255, 93);
}
body.vscode-high-contrast #lines-of-code-counter {
color: red;
}
③效果如下:
数字会跟随vscode的主题切换,而汉字则始终保持同一颜色
【图片待上传,截图待补充】
④完整的文件内容如下
src\extension.ts
import * as vscode from 'vscode';
const cats = {
'Coding Cat': 'https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif',
'Compiling Cat': 'https://media.giphy.com/media/mlvseq9yvZhba/giphy.gif',
'Testing Cat': 'https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif'
};
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.start', () => {
CatCodingPanel.createOrShow(context.extensionUri);
})
);
context.subscriptions.push(
vscode.commands.registerCommand('catCoding.doRefactor', () => {
if (CatCodingPanel.currentPanel) {
CatCodingPanel.currentPanel.doRefactor();
}
})
);
if (vscode.window.registerWebviewPanelSerializer) {
// Make sure we register a serializer in activation event
vscode.window.registerWebviewPanelSerializer(CatCodingPanel.viewType, {
async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) {
console.log(`Got state: ${state}`);
// Reset the webview options so we use latest uri for `localResourceRoots`.
webviewPanel.webview.options = getWebviewOptions(context.extensionUri);
CatCodingPanel.revive(webviewPanel, context.extensionUri);
}
});
}
}
function getWebviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions {
return {
// Enable javascript in the webview
enableScripts: true,
// And restrict the webview to only loading content from our extension's `media` directory.
localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'media')]
};
}
/**
* Manages cat coding webview panels
*/
class CatCodingPanel {
/**
* Track the currently panel. Only allow a single panel to exist at a time.
*/
public static currentPanel: CatCodingPanel | undefined;
public static readonly viewType = 'catCoding';
private readonly _panel: vscode.WebviewPanel;
private readonly _extensionUri: vscode.Uri;
private _disposables: vscode.Disposable[] = [];
public static createOrShow(extensionUri: vscode.Uri) {
const column = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: undefined;
// If we already have a panel, show it.
if (CatCodingPanel.currentPanel) {
CatCodingPanel.currentPanel._panel.reveal(column);
return;
}
// Otherwise, create a new panel.
const panel = vscode.window.createWebviewPanel(
CatCodingPanel.viewType,
'Cat Coding',
column || vscode.ViewColumn.One,
getWebviewOptions(extensionUri),
);
CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionUri);
}
public static revive(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
CatCodingPanel.currentPanel = new CatCodingPanel(panel, extensionUri);
}
private constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
this._panel = panel;
this._extensionUri = extensionUri;
// Set the webview's initial html content
this._update();
// Listen for when the panel is disposed
// This happens when the user closes the panel or when the panel is closed programmatically
this._panel.onDidDispose(() => this.dispose(), null, this._disposables);
// Update the content based on view changes
this._panel.onDidChangeViewState(
e => {
if (this._panel.visible) {
this._update();
}
},
null,
this._disposables
);
// Handle messages from the webview
this._panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'alert':
vscode.window.showErrorMessage(message.text);
return;
}
},
null,
this._disposables
);
}
public doRefactor() {
// Send a message to the webview webview.
// You can send any JSON serializable data.
this._panel.webview.postMessage({ command: 'refactor' });
}
public dispose() {
CatCodingPanel.currentPanel = undefined;
// Clean up our resources
this._panel.dispose();
while (this._disposables.length) {
const x = this._disposables.pop();
if (x) {
x.dispose();
}
}
}
private _update() {
const webview = this._panel.webview;
// Vary the webview's content based on where it is located in the editor.
switch (this._panel.viewColumn) {
case vscode.ViewColumn.Two:
this._updateForCat(webview, 'Compiling Cat');
return;
case vscode.ViewColumn.Three:
this._updateForCat(webview, 'Testing Cat');
return;
case vscode.ViewColumn.One:
default:
this._updateForCat(webview, 'Coding Cat');
return;
}
}
private _updateForCat(webview: vscode.Webview, catName: keyof typeof cats) {
this._panel.title = catName;
this._panel.webview.html = this._getHtmlForWebview(webview, cats[catName]);
}
private _getHtmlForWebview(webview: vscode.Webview, catGifPath: string) {
// Local path to main script run in the webview
const scriptPathOnDisk = vscode.Uri.joinPath(this._extensionUri, 'media', 'main.js');
// And the uri we use to load this script in the webview
const scriptUri = webview.asWebviewUri(scriptPathOnDisk);
// Local path to css styles
const styleResetPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'reset.css');
const stylesPathMainPath = vscode.Uri.joinPath(this._extensionUri, 'media', 'vscode.css');
// Uri to load styles into webview
const stylesResetUri = webview.asWebviewUri(styleResetPath);
const stylesMainUri = webview.asWebviewUri(stylesPathMainPath);
// Use a nonce to only allow specific scripts to be run
const nonce = getNonce();
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; img-src ${webview.cspSource} https:; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${stylesResetUri}" rel="stylesheet">
<link href="${stylesMainUri}" rel="stylesheet">
<title>Cat Coding</title>
</head>
<body>
<img src="${catGifPath}" width="300" />
<h1>我不应该变色</h1>
<h1 id="lines-of-code-counter">0</h1>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
}
function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
media\vscode.css
:root {
--container-padding: 20px;
--input-padding-vertical: 6px;
--input-padding-horizontal: 4px;
--input-margin-vertical: 4px;
--input-margin-horizontal: 0;
}
body {
padding: 0 var(--container-padding);
color: var(--vscode-foreground);
font-size: var(--vscode-font-size);
font-weight: var(--vscode-font-weight);
font-family: var(--vscode-font-family);
background-color: var(--vscode-editor-background);
}
ol,
ul {
padding-left: var(--container-padding);
}
body > *,
form > * {
margin-block-start: var(--input-margin-vertical);
margin-block-end: var(--input-margin-vertical);
}
*:focus {
outline-color: var(--vscode-focusBorder) !important;
}
a {
color: var(--vscode-textLink-foreground);
}
a:hover,
a:active {
color: var(--vscode-textLink-activeForeground);
}
code {
font-size: var(--vscode-editor-font-size);
font-family: var(--vscode-editor-font-family);
}
button {
border: none;
padding: var(--input-padding-vertical) var(--input-padding-horizontal);
width: 100%;
text-align: center;
outline: 1px solid transparent;
outline-offset: 2px !important;
color: var(--vscode-button-foreground);
background: var(--vscode-button-background);
}
button:hover {
cursor: pointer;
background: var(--vscode-button-hoverBackground);
}
button:focus {
outline-color: var(--vscode-focusBorder);
}
button.secondary {
color: var(--vscode-button-secondaryForeground);
background: var(--vscode-button-secondaryBackground);
}
button.secondary:hover {
background: var(--vscode-button-secondaryHoverBackground);
}
input:not([type='checkbox']),
textarea {
display: block;
width: 100%;
border: none;
font-family: var(--vscode-font-family);
padding: var(--input-padding-vertical) var(--input-padding-horizontal);
color: var(--vscode-input-foreground);
outline-color: var(--vscode-input-border);
background-color: var(--vscode-input-background);
}
input::placeholder,
textarea::placeholder {
color: var(--vscode-input-placeholderForeground);
}
/* #lines-of-code-counter {
color: aqua;
} */
body.vscode-light #lines-of-code-counter {
color: rgb(230, 8, 174);
}
body.vscode-dark #lines-of-code-counter{
color: rgb(239, 255, 93);
}
body.vscode-high-contrast #lines-of-code-counter {
color: red;
}
CSS的其他技巧
在编程中如果想要使用和vscode主题一样的颜色,怎么获取比较快呢?
- 使用CSS变量来获取,例如:
code {
color: var(--vscode-editor-foreground);
}
- 自动补全这些变量名,可以考虑使用vscode插件
除了颜色,还有字体也可以获取到:
--vscode-editor-font-family
- 编辑器字体系列(来自设置)。editor.fontFamily
--vscode-editor-font-weight
- 编辑器字体粗细(来自设置)。editor.fontWeight
--vscode-editor-font-size
- 编辑器字体大小(来自设置)。editor.fontSize
对特定主题设置样式
如果我们不满足于只对vscode的亮、暗、高对比三种主题设置各自的样式,而是想对其各自的主题分别设置样式,例如对主题《One Dark Pro》的样式进行设计,如下:
body[data-vscode-theme-id="One Dark Pro"] {
background: hotpink;
}
对于需要编写针对单个主题的 CSS 的特殊情况,webviews 的 body 元素具有一个名为 data 属性的数据属性,该属性存储当前活动主题的 ID。这使您可以为 Web 视图编写特定于主题的 CSS
支持的媒体格式:
音频:
- Wav
- Mp3
- Ogg
- Flac
视频: - H.264
- VP8
注意:使用视频时,需要保证视频轨道和音频轨道都是支持的,不然的话vscode就会播放视频,但是没有声音