在 VS Code 中试试

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 吗?

Webviews 非常棒,但也应谨慎使用,仅在 VS Code 的原生 API 不足时使用。Webviews 资源消耗高,并在与普通扩展不同的上下文中运行。设计糟糕的 webview 也可能轻易在 VS Code 中显得格格不入。

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

  • 此功能真的需要在 VS Code 中实现吗?作为单独的应用程序或网站会更好吗?

  • Webview 是实现你功能的唯一方式吗?你可以使用常规的 VS Code API 吗?

  • 你的 webview 会增加足够的用价值,足以证明其高昂的资源成本是合理的吗?

记住:能用 webview 实现某个功能,不代表你就应该这样做。但是,如果你确信需要使用 webview,那么本文档将为你提供帮助。让我们开始吧。

Webviews API 基础知识

为了解释 webview API,我们将构建一个名为 Cat Coding 的简单扩展。此扩展将使用 webview 显示一只猫正在编写代码(大概是在 VS Code 中)的 gif。随着我们深入学习 API,我们将继续为扩展添加功能,包括一个跟踪我们的猫编写了多少行源代码的计数器,以及在猫引入 bug 时通知用户的通知。

这是 Cat Coding 扩展第一个版本的 package.json。你可以在这里找到示例应用程序的完整代码。我们的扩展的第一个版本贡献了一个命令,名为 catCoding.start。当用户调用此命令时,我们将显示一个简单的 webview,其中包含我们的猫。用户可以从命令面板中以猫咪编程:开始新的猫咪编程会话的名称调用此命令,如果他们愿意,甚至可以为其创建快捷键。

{
  "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"
  }
}

注意:如果你的扩展目标版本低于 VS Code 1.74,则必须在 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,即使该 webview 继续在 VS Code 中显示。

与文本编辑器一样,用户也可以随时关闭 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
      );
    })
  );
}

扩展还可以通过调用其 dispose() 方法以编程方式关闭 webview。例如,如果我们想将猫咪的工作时间限制在五秒钟

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 面板拖动到新的编辑器列会将其移动到该新列中。

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

检查和调试 webviews

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

The developer tools

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

在开发者工具中,你可以使用开发者工具窗口左上角的检查工具开始检查 webview 的内容

Inspecting a webview using the developer tools

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

The developer tools console

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

Selecting the active frame

活动帧环境是 webview 脚本本身执行的地方。

此外,开发者:重新加载 Webview 命令会重新加载所有活动的 webview。这在你需要重置 webview 状态,或者磁盘上的某些 webview 内容已更改且你想加载新内容时非常有用。

加载本地内容

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

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

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!

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

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

使用 WebviewOptions.localResourceRoots 允许访问额外的本地资源。

你也可以始终使用 data URI 直接在 webview 中嵌入资源。

控制对本地资源的访问

Webviews 可以使用 localResourceRoots 选项控制可以从用户机器加载哪些资源。localResourceRoots 定义了一组根 URI,可以从这些 URI 加载本地内容。

我们可以使用 localResourceRootsCat Coding webviews 限制为仅从我们扩展中的 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 设置为 []

一般来说,webviews 在加载本地资源时应尽可能严格。但是,请记住 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,以确保视力障碍用户也能使用。

Webviews 还可以使用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 的 data 属性,它存储当前活动主题的 ID。这允许你为 webviews 编写特定主题的 CSS

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

支持的媒体格式

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

Webviews 中可以使用以下音频格式

  • Wav
  • Mp3
  • Ogg
  • Flac

Webviews 中可以使用以下视频格式

  • H.264
  • VP8

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

上下文菜单

高级 webviews 可以自定义用户在 webview 内部右键单击时显示的上下文菜单。这通过贡献点实现,类似于 VS Code 的常规上下文菜单,因此自定义菜单能很好地融入编辑器的其余部分。Webviews 还可以为 webview 的不同部分显示自定义上下文菜单。

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

"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

脚本和消息传递

Webviews 就像 iframes 一样,这意味着它们也可以运行脚本。Webviews 中的 JavaScript 默认是禁用的,但通过传入 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 脚本几乎可以做普通网页上的脚本可以做的任何事情。但请记住,webviews 存在于它们自己的上下文中,因此 webview 中的脚本无法访问 VS Code API。这就是消息传递的作用所在!

从扩展向 webview 传递消息

扩展可以使用 webview.postMessage() 向其 webviews 发送数据。此方法会将任何可 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 向扩展传递消息

Webviews 也可以将消息传回其扩展。这通过在 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 Workers

Webviews 内部支持Web Workers,但有一些重要的限制需要注意。

首先,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 再次变为可见时恢复状态。

getState 和 setState

在 webview 内部运行的脚本可以使用 getStatesetState 方法保存和恢复 JSON 可序列化的状态对象。即使 webview 面板隐藏时 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,你的 webviews 可以在 VS Code 重启时自动恢复。序列化基于 getStatesetState 构建,并且只有当你的扩展为你的 webviews 注册了 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 或无法快速保存和恢复状态的 webviews,你可以改用 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 可能很有吸引力,但请记住,它的内存开销很大,并且仅应在其他持久化技术不起作用时使用。

可访问性

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

后续步骤

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