Webview API

Webview API 允许扩展在 Visual Studio Code 中创建完全可自定义的视图。例如,内置的 Markdown 扩展使用 Webview 来呈现 Markdown 预览。Webview 还可以用于构建 VS Code 原生 API 所支持范围之外的复杂用户界面。

可以将 Webview 视为 VS Code 中一个由你的扩展程序控制的 iframe。Webview 可以在此框架内呈现几乎任何 HTML 内容,并通过消息传递与扩展进行通信。这种自由度使得 Webview 功能极其强大,并开启了全新的扩展可能性。

Webview 在以下几个 VS Code API 中被使用

  • 使用 createWebviewPanel 创建 Webview 面板。在这种情况下,Webview 面板在 VS Code 中显示为独立的编辑器。这使得它们非常适合展示自定义 UI 和自定义可视化效果。
  • 作为自定义编辑器的视图。自定义编辑器允许扩展为工作区中的任何文件提供自定义 UI。自定义编辑器 API 还允许你的扩展挂钩到编辑器事件(如撤销和重做)以及文件事件(如保存)。
  • 在侧边栏或面板区域中呈现的 Webview 视图中。有关详细信息,请参阅 Webview 视图示例扩展

本页面重点介绍基础的 Webview 面板 API,尽管此处涵盖的几乎所有内容也适用于自定义编辑器和 Webview 视图中使用的 Webview。即使你更感兴趣的是那些 API,我们也建议先阅读本页面,以熟悉 Webview 的基础知识。

VS Code API 使用

我应该使用 Webview 吗?

Webview 非常强大,但也应谨慎使用,仅在 VS Code 的原生 API 不足时才使用。Webview 非常消耗资源,并且在与普通扩展不同的上下文中运行。设计不当的 Webview 也很容易在 VS Code 中显得格格不入。

在使用 Webview 之前,请考虑以下事项

  • 此功能真的需要在 VS Code 内部实现吗?是否更适合作为一个独立的应用程序或网站?

  • Webview 是实现此功能的唯一途径吗?是否可以使用常规的 VS Code API 来代替?

  • 你的 Webview 所带来的用户价值是否足以抵消其高昂的资源成本?

记住:仅仅因为你可以用 Webview 实现某事,并不代表你应该这样做。然而,如果你确定需要使用 Webview,那么本文档旨在为你提供帮助。让我们开始吧。

Webview API 基础

为了解释 Webview API,我们将构建一个名为 Cat Coding(猫咪编程)的简单扩展。此扩展将使用 Webview 来显示一只猫正在编写代码(想必是在 VS Code 中)的 GIF 动图。在学习 API 的过程中,我们将继续为扩展添加功能,包括一个跟踪猫咪编写了多少行源代码的计数器,以及当猫咪引入 Bug 时通知用户的提醒。

这是 Cat Coding 扩展第一个版本的 package.json。你可以在此处找到示例应用程序的完整代码。该扩展的第一个版本贡献了一个命令,名为 catCoding.start。当用户调用此命令时,我们将显示一个包含猫咪的简单 Webview。用户可以从命令面板中以 Cat Coding: Start new cat coding session 的方式调用此命令,甚至可以为其创建快捷键(如果有需要的话)。

{
  "name": "cat-coding",
  "description": "Cat Coding",
  "version": "0.0.1",
  "publisher": "bierner",
  "engines": {
    "vscode": "^1.74.0"
  },
  "activationEvents": [],
  "main": "./out/extension.js",
  "contributes": {
    "commands": [
      {
        "command": "catCoding.start",
        "title": "Start new cat coding session",
        "category": "Cat Coding"
      }
    ]
  },
  "scripts": {
    "vscode:prepublish": "tsc -p ./",
    "compile": "tsc -watch -p ./",
    "postinstall": "node ./node_modules/vscode/bin/install"
  },
  "dependencies": {
    "vscode": "*"
  },
  "devDependencies": {
    "@types/node": "^9.4.6",
    "typescript": "^2.8.3"
  }
}

注意:如果你的扩展针对的是 1.74 之前的 VS Code 版本,则必须在 activationEvents 中显式列出 onCommand:catCoding.start

现在让我们实现 catCoding.start 命令。在扩展的主文件中,我们注册 catCoding.start 命令,并使用它来显示一个基础的 Webview

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.
      );
    })
  );
}

vscode.window.createWebviewPanel 函数在编辑器中创建并显示一个 Webview。如果你尝试以当前状态运行 catCoding.start 命令,你将看到以下内容

An empty webview

我们的命令打开了一个带有正确标题的新 Webview 面板,但没有内容!要将我们的猫咪添加到新面板,还需要使用 webview.html 来设置 Webview 的 HTML 内容

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>`;
}

如果你再次运行该命令,现在的 Webview 看起来是这样的

A webview with some HTML

进展不错!

webview.html 应始终是一个完整的 HTML 文档。HTML 片段或格式错误的 HTML 可能会导致意外行为。

更新 Webview 内容

webview.html 也可以在 Webview 创建后更新其内容。让我们利用这一点,通过引入猫咪轮换来使 Cat Coding 更加动态

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>`;
}

Updating the webview content

设置 webview.html 会替换整个 Webview 内容,类似于重新加载 iframe。当你开始在 Webview 中使用脚本时,这一点非常重要,因为这意味着设置 webview.html 也会重置脚本的状态。

上面的示例还使用了 webview.title 来更改编辑器中显示的文档标题。设置标题不会导致 Webview 重新加载。

生命周期

Webview 面板归创建它们的扩展所有。扩展必须持有从 createWebviewPanel 返回的 Webview 引用。如果你的扩展丢失了此引用,即使 Webview 继续在 VS Code 中显示,也无法再次重新获取对该 Webview 的访问权限。

与文本编辑器一样,用户也可以随时关闭 Webview 面板。当用户关闭 Webview 面板时,Webview 本身会被销毁。尝试使用已销毁的 Webview 会抛出异常。这意味着上面使用 setInterval 的示例实际上有一个严重的 Bug:如果用户关闭了面板,setInterval 将继续触发,并尝试更新 panel.webview.html,这当然会抛出异常。猫咪讨厌异常。让我们修复它!

当 Webview 被销毁时,会触发 onDidDispose 事件。我们可以使用此事件来取消后续更新并清理 Webview 的资源

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);
      };

      updateWebview();
      const interval = setInterval(updateWebview, 1000);

      panel.onDidDispose(
        () => {
          // When the panel is closed, cancel any future updates to the webview content
          clearInterval(interval);
        },
        null,
        context.subscriptions
      );
    })
  );
}

扩展也可以通过在 Webview 上调用 dispose() 来以编程方式关闭它们。例如,如果我们想把猫咪的工作日限制在五秒钟内

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');

      // After 5sec, programmatically close the webview panel
      const timeout = setTimeout(() => panel.dispose(), 5000);

      panel.onDidDispose(
        () => {
          // Handle user closing panel before the 5sec have passed
          clearTimeout(timeout);
        },
        null,
        context.subscriptions
      );
    })
  );
}

可见性和移动

当 Webview 面板被移动到后台标签页时,它会变隐藏。但它并不会被销毁。当面板再次被切换到前台时,VS Code 将自动从 webview.html 恢复 Webview 的内容

Webview content is automatically restored when the webview becomes visible again

.visible 属性用于告知你 Webview 面板当前是否可见。

扩展可以通过调用 reveal() 将 Webview 面板置于前台。此方法接受一个可选的目标视图列参数,用于显示面板。Webview 面板一次只能在一个编辑器列中显示。调用 reveal() 或将 Webview 面板拖动到新的编辑器列会将 Webview 移动到该新列中。

Webviews are moved when you drag them between tabs

让我们更新扩展,只允许同时存在一个 Webview。如果面板在后台,那么 catCoding.start 命令将把它带到前台

export function activate(context: vscode.ExtensionContext) {
  // Track the current panel with a webview
  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',
          columnToShowIn || vscode.ViewColumn.One,
          {}
        );
        currentPanel.webview.html = getWebviewContent('Coding Cat');

        // Reset when the current panel is closed
        currentPanel.onDidDispose(
          () => {
            currentPanel = undefined;
          },
          null,
          context.subscriptions
        );
      }
    })
  );
}

这是正在运行的新扩展

Using a single panel and reveal

每当 Webview 的可见性发生变化,或者 Webview 被移动到新列时,就会触发 onDidChangeViewState 事件。我们的扩展可以使用此事件来根据 Webview 显示所在的列来更换猫咪

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);
}

Responding to onDidChangeViewState events

检查和调试 Webview

Developer: Toggle Developer Tools 命令会打开一个 开发者工具窗口,你可以使用它来调试和检查你的 Webview。

The developer tools

请注意,如果你使用的是早于 1.56 版本的 VS Code,或者正在尝试调试设置了 enableFindWidget 的 Webview,则必须使用 Developer: Open Webview Developer Tools 命令。该命令为每个 Webview 打开一个专用的开发者工具页面,而不是使用所有 Webview 和编辑器本身共享的开发者工具页面。

从开发者工具中,你可以使用位于开发者工具窗口左上角的检查工具开始检查 Webview 的内容

Inspecting a webview using the developer tools

你还可以在开发者工具控制台中查看来自 Webview 的所有错误和日志

The developer tools console

要在 Webview 的上下文中评估表达式,请确保从开发者工具控制台面板左上角的下拉菜单中选择活动框架 (active frame) 环境

Selecting the active frame

活动框架环境是 Webview 脚本本身的执行环境。

此外,Developer: Reload Webview 命令会重新加载所有活动的 Webview。如果你需要重置 Webview 的状态,或者磁盘上的某些 Webview 内容发生了更改并希望加载新内容,这将非常有用。

加载本地内容

Webview 在隔离的上下文中运行,无法直接访问本地资源。这是出于安全原因考虑。这意味着为了从你的扩展加载图像、样式表和其他资源,或者从用户的当前工作区加载任何内容,你必须使用 Webview.asWebviewUri 函数将本地 file: URI 转换为 VS Code 可以用来加载本地资源子集的特殊 URI。

假设我们想开始将猫咪的 GIF 捆绑到我们的扩展中,而不是从 Giphy 拉取。为此,我们首先创建一个指向磁盘上文件的 URI,然后通过 asWebviewUri 函数传递这些 URI

import * as vscode from 'vscode';

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.joinPath(context.extensionUri, '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(catGifSrc: vscode.Uri) {
  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="${catGifSrc}" width="300" />
</body>
</html>`;
}

如果我们调试这段代码,会看到 catGifSrc 的实际值类似于

vscode-resource:/Users/toonces/projects/vscode-cat-coding/media/cat.gif

VS Code 能够识别这个特殊的 URI,并将使用它从磁盘加载我们的 GIF!

默认情况下,Webview 只能访问以下位置的资源

  • 扩展的安装目录内。
  • 用户当前活动工作区内。

使用 WebviewOptions.localResourceRoots 来允许访问其他本地资源。

你也可以始终使用 data URI 将资源直接嵌入到 Webview 中。

控制对本地资源的访问

Webview 可以通过 localResourceRoots 选项控制可以从用户计算机加载哪些资源。localResourceRoots 定义了一组根 URI,本地内容可以从中加载。

我们可以使用 localResourceRootsCat Coding Webview 限制为仅加载我们扩展中 media 目录下的资源

import * as vscode from 'vscode';

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,
        {
          // Only allow the webview to access resources in our extension's media directory
          localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'media')]
        }
      );

      const onDiskPath = vscode.Uri.joinPath(context.extensionUri, 'media', 'cat.gif');
      const catGifSrc = panel.webview.asWebviewUri(onDiskPath);

      panel.webview.html = getWebviewContent(catGifSrc);
    })
  );
}

要禁止所有本地资源,只需将 localResourceRoots 设置为 []

通常,Webview 在加载本地资源时应尽可能严格。但是,请记住 localResourceRoots 本身并不能提供完全的安全保护。确保你的 Webview 也遵循安全最佳实践,并添加内容安全策略以进一步限制可加载的内容。

Webview 内容主题化

Webview 可以使用 CSS 根据 VS Code 的当前主题更改其外观。VS Code 将主题分为三类,并向 body 元素添加一个特殊的类来指示当前主题

  • vscode-light - 浅色主题。
  • vscode-dark - 深色主题。
  • vscode-high-contrast - 高对比度主题。

以下 CSS 根据用户的当前主题更改 Webview 的文本颜色

body.vscode-light {
  color: black;
}

body.vscode-dark {
  color: white;
}

body.vscode-high-contrast {
  color: red;
}

在开发 Webview 应用程序时,请确保它适用于这三种类型的主题。并务必在高对比度模式下测试你的 Webview,以确保视障人士可以使用它。

Webview 还可以使用 CSS 变量访问 VS Code 主题颜色。这些变量名称以 vscode 为前缀,并将 . 替换为 -。例如 editor.foreground 变为 var(--vscode-editor-foreground)

code {
  color: var(--vscode-editor-foreground);
}

查阅主题颜色参考以获取可用的主题变量。有一个扩展程序可提供这些变量的 IntelliSense 建议。

此外还定义了以下与字体相关的变量

  • --vscode-editor-font-family - 编辑器字体系列(来自 editor.fontFamily 设置)。
  • --vscode-editor-font-weight - 编辑器字体粗细(来自 editor.fontWeight 设置)。
  • --vscode-editor-font-size - 编辑器字体大小(来自 editor.fontSize 设置)。

最后,对于需要编写针对单一主题的 CSS 的特殊情况,Webview 的 body 元素具有一个名为 vscode-theme-id 的数据属性,它存储了当前活动主题的 ID。这让你能够为 Webview 编写主题特定的 CSS

body[data-vscode-theme-id="One Dark Pro"] {
    background: hotpink;
}

支持的媒体格式

Webview 支持音频和视频,但并非支持所有媒体编解码器或媒体文件容器类型。

可以在 Webview 中使用以下音频格式

  • Wav
  • Mp3
  • Ogg
  • Flac

可以在 Webview 中使用以下视频格式

  • H.264
  • VP8

对于视频文件,请确保视频和音频轨道的媒体格式均受支持。例如,许多 .mp4 文件使用 H.264 编码视频和 AAC 编码音频。VS Code 将能够播放 mp4 的视频部分,但由于不支持 AAC 音频,因此将没有声音。相反,你需要将 mp3 用于音频轨道。

上下文菜单

高级 Webview 可以自定义用户在 Webview 内右键单击时显示的上下文菜单。这是使用贡献点以类似于 VS Code 常规上下文菜单的方式完成的,因此自定义菜单可以与编辑器的其余部分完美契合。Webview 还可以为 Webview 的不同部分显示自定义上下文菜单。

要向你的 Webview 添加新的上下文菜单项,首先在新的 webview/context 部分下的 menus 中添加一个新条目。每个贡献都需要一个 command(这也是项目标题的来源)和一个 when 子句。when 子句应包含 webviewId == 'YOUR_WEBVIEW_VIEW_TYPE',以确保上下文菜单仅适用于你的扩展程序的 Webview

"contributes": {
  "menus": {
    "webview/context": [
      {
        "command": "catCoding.yarn",
        "when": "webviewId == 'catCoding'"
      },
      {
        "command": "catCoding.insertLion",
        "when": "webviewId == 'catCoding' && webviewSection == 'editor'"
      }
    ]
  },
  "commands": [
    {
      "command": "catCoding.yarn",
      "title": "Yarn 🧶",
      "category": "Cat Coding"
    },
    {
      "command": "catCoding.insertLion",
      "title": "Insert 🦁",
      "category": "Cat Coding"
    },
    ...
  ]
}

在 webview 内部,您还可以使用 data-vscode-context 数据属性(或在 JavaScript 中使用 dataset.vscodeContext)设置 HTML 特定区域的上下文。data-vscode-context 值是一个 JSON 对象,它指定当用户右键单击元素时要设置的上下文。最终上下文是从文档根到单击的元素确定的。

例如,考虑以下 HTML

<div class="main" data-vscode-context='{"webviewSection": "main", "mouseCount": 4}'>
  <h1>Cat Coding</h1>

  <textarea data-vscode-context='{"webviewSection": "editor", "preventDefaultContextMenuItems": true}'></textarea>
</div>

如果用户右键单击 textarea,将设置以下上下文

  • webviewSection == 'editor' - 这将覆盖来自父元素的 webviewSection
  • mouseCount == 4 - 这是从父元素继承的。
  • preventDefaultContextMenuItems == true - 这是一个特殊上下文,用于隐藏 VS Code 通常添加到 Webview 上下文菜单中的复制和粘贴条目。

如果用户在 <textarea> 内右键单击,他们将看到

Custom context menus showing in a webview

有时在左键/主要单击时显示菜单很有用。例如,在拆分按钮上显示菜单。你可以通过在 onClick 事件中分发 contextmenu 事件来实现这一点

<button data-vscode-context='{"preventDefaultContextMenuItems": true }' onClick='((e) => {
        e.preventDefault();
        e.target.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, clientX: e.clientX, clientY: e.clientY }));
        e.stopPropagation();
    })(event)'>Create</button>

Split button with a menu

脚本和消息传递

Webview 就像 iframes,这意味着它们也可以运行脚本。JavaScript 在 Webview 中默认是禁用的,但可以通过传入 enableScripts: true 选项轻松重新启用。

让我们使用脚本添加一个计数器,跟踪我们的猫咪编写的源代码行数。运行一个基础脚本非常简单,但请注意此示例仅用于演示目的。在实践中,你的 Webview 应始终使用内容安全策略禁用内联脚本

import * as path from 'path';
import * as vscode from 'vscode';

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,
        {
          // Enable scripts in the webview
          enableScripts: true
        }
      );

      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" />
    <h1 id="lines-of-code-counter">0</h1>

    <script>
        const counter = document.getElementById('lines-of-code-counter');

        let count = 0;
        setInterval(() => {
            counter.textContent = count++;
        }, 100);
    </script>
</body>
</html>`;
}

A script running in a webview

哇!那只猫可真高产。

Webview 脚本几乎可以执行普通网页脚本能做的任何事情。但请记住,Webview 存在于它们自己的上下文中,因此 Webview 中的脚本无法访问 VS Code API。这就是消息传递的用武之地!

从扩展向 Webview 传递消息

扩展可以使用 webview.postMessage() 向其 Webview 发送数据。此方法将任何可 JSON 序列化的数据发送到 Webview。消息通过标准的 message 事件在 Webview 内部接收。

为了演示这一点,让我们向 Cat Coding 添加一个新命令,指示当前正在编码的猫咪重构其代码(从而减少代码总行数)。新的 catCoding.doRefactor 命令使用 postMessage 将指令发送到当前的 Webview,并在 Webview 内部使用 window.addEventListener('message', event => { ... }) 来处理该消息

export function activate(context: vscode.ExtensionContext) {
  // Only allow a single Cat Coder
  let currentPanel: vscode.WebviewPanel | undefined = undefined;

  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.start', () => {
      if (currentPanel) {
        currentPanel.reveal(vscode.ViewColumn.One);
      } else {
        currentPanel = vscode.window.createWebviewPanel(
          'catCoding',
          'Cat Coding',
          vscode.ViewColumn.One,
          {
            enableScripts: true
          }
        );
        currentPanel.webview.html = getWebviewContent();
        currentPanel.onDidDispose(
          () => {
            currentPanel = undefined;
          },
          undefined,
          context.subscriptions
        );
      }
    })
  );

  // Our new command
  context.subscriptions.push(
    vscode.commands.registerCommand('catCoding.doRefactor', () => {
      if (!currentPanel) {
        return;
      }

      // Send a message to our webview.
      // You can send any JSON serializable data.
      currentPanel.webview.postMessage({ command: 'refactor' });
    })
  );
}

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" />
    <h1 id="lines-of-code-counter">0</h1>

    <script>
        const counter = document.getElementById('lines-of-code-counter');

        let count = 0;
        setInterval(() => {
            counter.textContent = count++;
        }, 100);

        // Handle the message inside the webview
        window.addEventListener('message', event => {

            const message = event.data; // The JSON data our extension sent

            switch (message.command) {
                case 'refactor':
                    count = Math.ceil(count * 0.5);
                    counter.textContent = count;
                    break;
            }
        });
    </script>
</body>
</html>`;
}

Passing messages to a webview

从 Webview 向扩展传递消息

Webview 也可以将消息传回其扩展。这是通过 Webview 内部的一个特殊 VS Code API 对象上的 postMessage 函数完成的。要访问 VS Code API 对象,请在 Webview 内部调用 acquireVsCodeApi。此函数每个会话只能调用一次。你必须保留此方法返回的 VS Code API 实例,并将其提供给任何需要使用它的其他函数。

我们可以在 Cat Coding Webview 中使用 VS Code API 和 postMessage,以便在我们的猫咪引入 Bug 时提醒扩展

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,
        {
          enableScripts: true
        }
      );

      panel.webview.html = getWebviewContent();

      // Handle messages from the webview
      panel.webview.onDidReceiveMessage(
        message => {
          switch (message.command) {
            case 'alert':
              vscode.window.showErrorMessage(message.text);
              return;
          }
        },
        undefined,
        context.subscriptions
      );
    })
  );
}

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" />
    <h1 id="lines-of-code-counter">0</h1>

    <script>
        (function() {
            const vscode = acquireVsCodeApi();
            const counter = document.getElementById('lines-of-code-counter');

            let count = 0;
            setInterval(() => {
                counter.textContent = count++;

                // Alert the extension when our cat introduces a bug
                if (Math.random() < 0.001 * count) {
                    vscode.postMessage({
                        command: 'alert',
                        text: '🐛  on line ' + count
                    })
                }
            }, 100);
        }())
    </script>
</body>
</html>`;
}

Passing messages from the webview to the main extension

出于安全原因,你必须保持 VS Code API 对象私有,并确保它永远不会泄露到全局作用域中。

使用 Web Worker

Webview 内部支持 Web Worker,但需要注意一些重要的限制。

首先,Worker 只能使用 data:blob: URI 加载。你不能直接从你的扩展文件夹中加载 Worker。

如果你确实需要从扩展中的 JavaScript 文件加载 Worker 代码,请尝试使用 fetch

const workerSource = 'absolute/path/to/worker.js';

fetch(workerSource)
  .then(result => result.blob())
  .then(blob => {
    const blobUrl = URL.createObjectURL(blob);
    new Worker(blobUrl);
  });

Worker 脚本也不支持使用 importScriptsimport(...) 导入源代码。如果你的 Worker 动态加载代码,请尝试使用诸如 webpack 之类的打包工具将 Worker 脚本打包成单个文件。

使用 webpack,你可以使用 LimitChunkCountPlugin 强制将编译后的 Worker JavaScript 压缩为单个文件

const path = require('path');
const webpack = require('webpack');

module.exports = {
  target: 'webworker',
  entry: './worker/src/index.js',
  output: {
    filename: 'worker.js',
    path: path.resolve(__dirname, 'media')
  },
  plugins: [
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 1
    })
  ]
};

安全性

与任何网页一样,在创建 Webview 时,你必须遵循一些基本的安全最佳实践。

限制能力

Webview 应具备其所需的最少功能集。例如,如果你的 Webview 不需要运行脚本,请不要设置 enableScripts: true。如果你的 Webview 不需要从用户的工作区加载资源,请将 localResourceRoots 设置为 [vscode.Uri.file(extensionContext.extensionPath)] 甚至 [] 以禁止访问所有本地资源。

内容安全策略

内容安全策略进一步限制了可以在 Webview 中加载和执行的内容。例如,内容安全策略可以确保只有允许的脚本列表才能在 Webview 中运行,甚至告诉 Webview 只能通过 https 加载图像。

要添加内容安全策略,请在 Webview 的 <head> 顶部放置一个 <meta http-equiv="Content-Security-Policy"> 指令

function getWebviewContent() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <meta http-equiv="Content-Security-Policy" content="default-src 'none';">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Cat Coding</title>
</head>
<body>
    ...
</body>
</html>`;
}

策略 default-src 'none'; 禁止所有内容。然后,我们可以重新开启扩展运行所需的最小内容量。这是一个允许加载本地脚本和样式表,并仅通过 https 加载图像的内容安全策略

<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'none'; img-src ${webview.cspSource} https:; script-src ${webview.cspSource}; style-src ${webview.cspSource};"
/>

${webview.cspSource} 值是一个来自 Webview 对象本身的值的占位符。有关如何使用此值的完整示例,请参阅 Webview 示例

此内容安全策略还隐式禁用了内联脚本和样式。最佳做法是将所有内联样式和脚本提取到外部文件中,以便可以在不放宽内容安全策略的情况下正确加载它们。

仅通过 https 加载内容

如果你的 Webview 允许加载外部资源,强烈建议你仅允许通过 https 而非 http 加载这些资源。上面的内容安全策略示例已经通过仅允许通过 https: 加载图像来实现这一点。

清理所有用户输入

正如你在普通网页中所做的那样,在构建 Webview 的 HTML 时,必须清理所有用户输入。未能正确清理输入可能会导致内容注入,这可能会使你的用户面临安全风险。

必须清理的示例值

  • 文件内容。
  • 文件和文件夹路径。
  • 用户和工作区设置。

考虑使用辅助库来构建 HTML 字符串,或者至少确保正确清理来自用户工作区的所有内容。

切勿仅依赖清理来保证安全。请确保遵循其他安全最佳实践,例如设置内容安全策略,以最大程度地减少任何潜在内容注入的影响。

持久性

在标准的 Webview 生命周期中,Webview 由 createWebviewPanel 创建,并在用户关闭它们或调用 .dispose() 时销毁。然而,Webview 的内容是在 Webview 变为可见时创建的,并在 Webview 移至后台时销毁。当 Webview 被移动到后台标签页时,Webview 内部的任何状态都将丢失。

解决此问题的最佳方法是使你的 Webview 无状态。使用消息传递来保存 Webview 的状态,然后在 Webview 再次可见时恢复该状态。

getState 和 setState

在 Webview 内部运行的脚本可以使用 getStatesetState 方法来保存和恢复 JSON 可序列化的状态对象。即使 Webview 面板隐藏后其内容被销毁,此状态也会持久存在。当 Webview 面板被销毁时,该状态也会被销毁。

// Inside a webview script
const vscode = acquireVsCodeApi();

const counter = document.getElementById('lines-of-code-counter');

// Check if we have an old state to restore from
const previousState = vscode.getState();
let count = previousState ? previousState.count : 0;
counter.textContent = count;

setInterval(() => {
  counter.textContent = count++;
  // Update the saved state
  vscode.setState({ count });
}, 100);

getStatesetState 是持久化状态的首选方式,因为它们的性能开销远低于 retainContextWhenHidden

序列化

通过实现 WebviewPanelSerializer,你的 Webview 可以在 VS Code 重启时自动恢复。序列化建立在 getStatesetState 的基础之上,并且仅在你的扩展为 Webview 注册了 WebviewPanelSerializer 时才启用。

为了使我们的猫咪编码面板在 VS Code 重启后持久存在,首先在扩展的 package.json 中添加一个 onWebviewPanel 激活事件

"activationEvents": [
    ...,
    "onWebviewPanel:catCoding"
]

此激活事件确保每当 VS Code 需要恢复 viewType 为 catCoding 的 Webview 时,我们的扩展都会被激活。

然后,在扩展的 activate 方法中,调用 registerWebviewPanelSerializer 来注册一个新的 WebviewPanelSerializerWebviewPanelSerializer 负责从其持久化状态中恢复 Webview 的内容。此状态就是 Webview 内容使用 setState 设置的 JSON blob。

export function activate(context: vscode.ExtensionContext) {
  // Normal setup...

  // And make sure we register a serializer for our webview type
  vscode.window.registerWebviewPanelSerializer('catCoding', new CatCodingSerializer());
}

class CatCodingSerializer implements vscode.WebviewPanelSerializer {
  async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) {
    // `state` is the state persisted using `setState` inside the webview
    console.log(`Got state: ${state}`);

    // Restore the content of our webview.
    //
    // Make sure we hold on to the `webviewPanel` passed in here and
    // also restore any event listeners we need on it.
    webviewPanel.webview.html = getWebviewContent();
  }
}

现在,如果你在打开猫咪编码面板的情况下重启 VS Code,该面板将自动恢复到相同的编辑器位置。

retainContextWhenHidden

对于具有非常复杂的 UI 或无法快速保存和恢复的状态的 Webview,你可以改为使用 retainContextWhenHidden 选项。此选项使 Webview 即使在本身不再处于前台时,也能保留其内容,但处于隐藏状态。

尽管 Cat Coding 几乎谈不上拥有复杂的状态,但让我们尝试启用 retainContextWhenHidden,看看该选项如何改变 Webview 的行为

import * as vscode from 'vscode';

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,
        {
          enableScripts: true,
          retainContextWhenHidden: true
        }
      );
      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" />
    <h1 id="lines-of-code-counter">0</h1>

    <script>
        const counter = document.getElementById('lines-of-code-counter');

        let count = 0;
        setInterval(() => {
            counter.textContent = count++;
        }, 100);
    </script>
</body>
</html>`;
}

retainContextWhenHidden demo

请注意,现在当 Webview 被隐藏再恢复时,计数器不会重置。无需额外代码!使用 retainContextWhenHidden,Webview 的行为类似于 Web 浏览器中的后台标签页。即使标签页未激活或不可见,脚本和其他动态内容也会继续运行。当启用 retainContextWhenHidden 时,你还可以向隐藏的 Webview 发送消息。

虽然 retainContextWhenHidden 可能很吸引人,但请记住它具有较高的内存开销,并且仅应在其他持久化技术无法生效时使用。

辅助功能

vscode-using-screen-reader 将在用户使用屏幕阅读器操作 VS Code 的上下文中添加到 Webview 的主 body 中。此外,如果用户表达了减少窗口动画效果的偏好,类 vscode-reduce-motion 将被添加到文档的主 body 元素中。通过观察这些类并相应地调整你的渲染,你的 Webview 内容可以更好地反映用户的偏好。

后续步骤

如果你想了解更多关于 VS Code 可扩展性的信息,请尝试以下主题

© . This site is unofficial and not affiliated with Microsoft.