> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Chrome内置AI的扩展开发实验
- URL: https://www.hubwiz.com/blog/chrome-built-in-ai-experiment/
- Published: 2024-12-03T07:19:29.000Z
- Updated: 2024-12-03T07:19:29.000Z
- Description: 本文介绍如何构建一个基于 Chrome 内置AI的扩展程序，它使用 Summarization API 来总结你在网页上选择的任何文本。
- Author: admin
- Tags: LIBRARY, CHROME, SUMMARIZER API, CHROME EXTENSION, #Import 2026-10-14 14:41

本系列的一个重点是了解 Chrome 内置 AI API 的各种功能并增强现有的 Web 应用程序。

在本系列的这一部分中，我们将研究如何构建一个 Chrome 扩展程序，该扩展程序将作为侧面板或通过操作菜单提供，它将在后台使用 Summarization API 来总结你在网页上选择的任何文本。

## 1、Chrome 扩展的演示

它有助于理解我们要构建的内容。所以让我们看看 Chrome 扩展程序的实际操作。

![](https://www.hubwiz.com/blog/content/images/2024/12/image-104.png)

演示很简单。

- 在任何网页上，你选择一些文本，然后调用 Summarize。
- Chrome 扩展程序侧面板打开并显示总结的结果。

在后台，扩展程序调用了我们在本系列上一部分中看到的[ Summarization API](https://github.com/WICG/writing-assistance-apis?ref=hubwiz.com)。

## 2、Chrome 扩展实现代码

扩展程序的完整代码可在[这个存储库](https://github.com/rominirani/chrome-built-in-ai-experiments/tree/main/chrome-extension-summarizer?source=post%5Fpage-----76f12a47a523--------------------------------)中找到。请按照步骤先安装 Chrome 扩展程序。[README.md](https://github.com/rominirani/chrome-built-in-ai-experiments/blob/main/chrome-extension-summarizer/README.MD?ref=hubwiz.com) 文件包含完整的说明。

Chrome 扩展程序代码遵循我从 Chrome 扩展程序示例文件夹中挑选的一个示例，该示例演示了如何根据操作在 Chrome 扩展程序中打开侧面板。我们代码中的操作是选择文本，右键单击，然后从上下文菜单中调用 `Summarize`操作。

你必须熟悉编写 Chrome 扩展程序，即使不熟悉，我建议你查看以下两个链接：

- [编写 Hello World Chrome 扩展程序](https://developer.chrome.com/docs/extensions/get-started/tutorial/hello-world?ref=hubwiz.com)
- [侧面板 Chrome 扩展程序示例](https://developer.chrome.com/docs/extensions/get-started/tutorial/hello-world?ref=hubwiz.com)

让我们根据可用文件分解代码的关键部分：

### 2.1 manifest.json

我们有一些标准属性。需要注意的关键是我们正在配置侧面板，即 `sidepanel.html` 文件。我们有一个如上所述的后台 `service_worker`。相应的权限在那里：我们需要 `contextMenus`，因为我们将向其添加一个总结操作。此外，我们还有存储权限，这是示例演示的一个巧妙技巧。存储将保存要汇总的文本，即使在从上下文菜单调用汇总功能之前打开了侧面板，也可以使用该文本。

```
{
    "name": "Chrome built-in AI Summarization Side Panel",
    "version": "1.0",
    "manifest_version": 3,
    "description": "Provides a summary of the selected text",
    "background": {
      "service_worker": "service-worker.js"
    },
    "icons": {
      "128": "images/icon-128.png",
      "16": "images/icon-16.png"
    },
    "side_panel": {
      "default_path": "sidepanel.html"
    },
    "permissions": ["sidePanel", "contextMenus", "storage"]
  }
```

一旦我们解决了 `manifest.json` 问题，让我们看看后台 `service-worker.js` 文件，如下所示：

```
function setupContextMenu() {
    chrome.contextMenus.create({
      id: 'summarize-text',
      title: 'Summarize',
      contexts: ['selection']
    });
  }
  
  chrome.runtime.onInstalled.addListener(() => {
    setupContextMenu();
  });
  
  chrome.contextMenus.onClicked.addListener((data, tab) => {
    // Store the last word in chrome.storage.session.
    chrome.storage.session.set({ lastTextToSummarize: data.selectionText });
  
    // Make sure the side panel is open.
    chrome.sidePanel.open({ tabId: tab.id });
  });
```

代码可以理解如下：

- 安装 Chrome 扩展程序时，它会调用 `setupContextMenu` 方法，该方法只不过是将我们的 `Summarize` 操作添加到其中。上下文是要选择的文本。
- 如果单击了 `Summarizeaction`，它将使用会话存储来保存要汇总的文本。这只不过是用户选择的文本。然后它将打开侧面板，所有神奇的事情都发生在其中。我指的神奇之处在于我们将在侧面板内调用的 Chrome 内置 AI Summarization API。

### 2.2 sidePanel.html

这是我们侧面板的 HTML 内容。除了位置之外，它没有太多其他内容说明和最终摘要结果的持有者。需要注意的关键是 `sidepanel.js` 文件，该文件将包含对 Chrome 内置 AI 摘要 API 的调用。

```
<html>
  <head>
    <title>Chrome Built-in AI Summarization Panel</title>
  </head>
  <body>
    <h1>Summary</h1>
    <hr />
    <p id="select-text-to-summarize">Select the text that you would like to get summary on.</p>
    <div>
      <p id="summarization-text"></p>
    </div>
    <script src="sidepanel.js"></script>
  </body>
</html>
```

### 2.3 sidePanel.js 

```
async function chromeAISummarizeText(textToSummarize) {
    if (!textToSummarize) return;
  
    document.body.querySelector('#summarization-text').innerText = "Summarizing...";
  
    // Use await to wait for the fetch request to complete
    try {
        // Check for browser AI support
        const summarizerCapabilities = await ai.summarizer.capabilities();
        if (summarizerCapabilities.available === 'no') {
            console.log('Text Summarizer API not available in this browser.');
            return;
        }

        const keyPointsSummarizer = await ai.summarizer.create({ type: 'key-points', format: 'plain-text' });
        const tlDrSummaryText = await keyPointsSummarizer.summarize(textToSummarize);
        document.body.querySelector('#summarization-text').innerText = tlDrSummaryText;
    } catch (error) {
        console.error('Summarization error:', error);
        document.body.querySelector('#summarization-text').innerText = 'Error summarizing text.';
    }
  }

chrome.storage.session.get('lastTextToSummarize', ({ lastTextToSummarize }) => {
    chromeAISummarizeText(lastTextToSummarize);
  });
  
chrome.storage.session.onChanged.addListener(async (changes) => {
    const lastTextToSummarizeChange = changes['lastTextToSummarize'];
  
    if (!lastTextToSummarizeChange) {
      return;
    }
    await chromeAISummarizeText(lastTextToSummarizeChange.newValue);
});
```

让我们从顶部分解这段代码。

首先是我们的异步 `chromeAISummarizeText` 函数，它接收要汇总的文本。然后你会发现它具有我们在上一部分中用于汇总文本的相同代码。它首先检查 `ai.summarizer` 是否可用。如果是，那么它将首先创建 `ai.summarizerobject`，类型为 `key-points`。然后它将调用汇总函数，然后将结果显示在我们在 `sidepanel.html` 中定义的 `div` 的相关部分中。

其他两个事件处理程序是 `storage.session` 对象上的标准事件处理程序，用于对 `lastTextToSummarizekey` 的任何更改。请记住，这是我们在 `service_worker.js` 中设置相同的地方

一旦值发生变化或获得值，我们就会调用我们在上面第 1 点中看到的相同 `chromeAISummarizeText` 方法。

再次供你参考，这里有一个示例运行：

![](https://www.hubwiz.com/blog/content/images/2024/12/image-105.png)

## 3、结束语

希望你现在能够想到使用 Chrome 内置 AI API 改进现有 Chrome 扩展程序的各种方法。虽然这仍然不是一个标准，但它有助于了解本地 AI 推理和访问这些专用模型如何开辟新的用例和/或改善你现有的用户体验。

---

原文链接：[Chrome Built-in AI Experiments: Summarizer Chrome Extension](https://medium.com/google-cloud/chrome-built-in-ai-experiments-summarizer-chrome-extension-76f12a47a523?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处