浏览器插件开发

2025-07-10 14:58:22阅读 29评论 0

1.配置文件

{
    "name": "Hello Extensions",
    "description": "Base Level Extension",
    "version": "1.0",
    "manifest_version": 3,
    "icons": {
        "16": "icons/icon16.png",
        "32": "icons/icon32.png",
        "48": "icons/icon48.png",
        "128": "icons/icon128.png"
      },
    "action": {
      "default_popup": "hello.html",
      "default_icon": "boss.png"
    },
    "permissions": [
        "contextMenus",
        "storage",
        "activeTab",
        "scripting"
    ],
    "background": {
      "service_worker": "background.js"
    },
    "content_scripts": [
        {
          "js": ["scripts/content.js"],
          "matches": [
            "https://developer.chrome.com/docs/extensions/*",
            "https://developer.chrome.com/docs/webstore/*"
          ]
        }
      ]
  }

让我们逐项分析这个扩展的配置文件:

1) 基本信息

  • name: "Hello Extensions" - 扩展的显示名称
  • description: "Base Level Extension" - 扩展的描述信息
  • version: "1.0" - 扩展的版本号
  • manifest_version: 3 - 使用 Manifest V3 规范

2) 图标配置

"icons": {
    "16": "icons/icon16.png",
    "32": "icons/icon32.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
}

定义了不同尺寸的扩展图标,用于不同场景显示(工具栏、扩展管理页面等)

3) 操作配置

"action": {
    "default_popup": "hello.html",
    "default_icon": "boss.png"
}
  • default_popup: 点击扩展图标时显示的弹出页面
  • default_icon: 工具栏中显示的图标

4) 权限申请

"permissions": [
    "contextMenus",  // 右键菜单
    "storage",       // 存储功能
    "activeTab",     // 当前标签页
    "scripting"      // 脚本注入
]

5) 后台配置

"background": {
    "service_worker": "background.js"
}

指定后台服务工作线程脚本,用于处理扩展的后台逻辑

6) 内容脚本

"content_scripts": [
    {
        "js": ["scripts/content.js"],
        "matches": [
            "https://developer.chrome.com/docs/extensions/*",
            "https://developer.chrome.com/docs/webstore/*"
        ]
    }
]
  • js: 指定要注入的 JavaScript 文件
  • matches: 定义在哪些页面上注入脚本(使用 URL 匹配模式)

这个配置文件定义了一个基本的 Chrome 扩展,具有弹出界面、后台进程和内容脚本功能,可以在特定的 Chrome 开发者文档页面上运行。

2.注入脚本案例

content.js内容

function renderReadingTime(article) {
    // If we weren't provided an article, we don't need to render anything.
    if (!article) {
      return;
    }

    const text = article.textContent;
    const wordMatchRegExp = /[^\s]+/g; // Regular expression
    const words = text.matchAll(wordMatchRegExp);
    // matchAll returns an iterator, convert to array to get word count
    const wordCount = [...words].length;
    const readingTime = Math.round(wordCount / 200);
    const badge = document.createElement("p");
    // Use the same styling as the publish information in an article's header
    badge.classList.add("color-secondary-text", "type--caption");
    badge.textContent = `⏱️ ${readingTime} min read`;

    // Support for API reference docs
    const heading = article.querySelector("h1");
    // Support for article docs with date
    const date = article.querySelector("time")?.parentNode;

    (date ?? heading).insertAdjacentElement("afterend", badge);
  }

  renderReadingTime(document.querySelector("article"));

这是一个 Chrome 扩展的内容脚本,用于计算文章阅读时间并显示在页面上。让我们逐部分分析:

主要功能

renderReadingTime 函数接收一个 article 元素参数,计算并显示文章的预计阅读时间。

代码详细分析

1) 输入检查

if (!article) {
    return;
}

首先检查是否提供了文章元素,如果没有则直接返回。

2) 字数统计

const text = article.textContent;
const wordMatchRegExp = /[^\s]+/g; // 匹配非空白字符
const words = text.matchAll(wordMatchRegExp);
const wordCount = [...words].length;
  • 获取文章文本内容
  • 使用正则表达式匹配单词
  • 将匹配结果转换为数组并计算长度

3) 阅读时间计算

const readingTime = Math.round(wordCount / 200);

假设平均阅读速度为每分钟200词,计算预计阅读时间。

4) 创建显示徽章

const badge = document.createElement("p");
badge.classList.add("color-secondary-text", "type--caption");
badge.textContent = `⏱️ ${readingTime} min read`;
  • 创建段落元素作为徽章
  • 添加样式类
  • 设置显示内容,包含时钟表情符号

5) 插入徽章

const heading = article.querySelector("h1");
const date = article.querySelector("time")?.parentNode;
(date ?? heading).insertAdjacentElement("afterend", badge);
  • 查找文章标题或日期元素
  • 使用空值合并操作符(??)选择插入位置
  • 将徽章插入到选定元素之后

6) 执行函数

renderReadingTime(document.querySelector("article"));

查找页面中的 article 元素并执行函数。

使用场景

根据 manifest.json 的配置,这个脚本会在 Chrome 开发者文档网站上运行,为文章添加预计阅读时间的显示。这是一个实用的功能,可以帮助用户快速评估阅读文章所需的时间。

3.百度翻译案例

background.js 内容

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "translate-selection",
    title: "百度翻译:%s",
    contexts: ["selection"],
  });
});
chrome.contextMenus.onClicked.addListener((info, tab) => {  
    if (info.menuItemId === "translate-selection") {
        const selectedText = info.selectionText;
        const url = `https://fanyi.baidu.com/#auto/zh/${encodeURIComponent(selectedText)}`;
        if (selectedText) {
        chrome.tabs.create({ url: url });
        }
    }
});

这是扩展的后台脚本,主要实现了右键菜单翻译功能。让我们分析主要部分:

1) 安装监听器

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "translate-selection",
    title: "百度翻译:%s",
    contexts: ["selection"],
  });
});
  • onInstalled: 在扩展安装或更新时触发
  • contextMenus.create: 创建右键菜单项
    • id: 菜单项唯一标识
    • title: 菜单项显示文本(%s 会被选中的文本替换)
    • contexts: 指定菜单项出现的上下文(这里是选中文本时)

2) 菜单点击处理

chrome.contextMenus.onClicked.addListener((info, tab) => {  
    if (info.menuItemId === "translate-selection") {
        const selectedText = info.selectionText;
        const url = `https://fanyi.baidu.com/#auto/zh/${encodeURIComponent(selectedText)}`;
        if (selectedText) {
            chrome.tabs.create({ url: url });
        }
    }
});
  • onClicked: 监听右键菜单点击事件
  • 检查点击的菜单项是否为翻译选项
  • 获取选中的文本
  • 构造百度翻译 URL(使用 encodeURIComponent 处理特殊字符)
  • 如果有选中文本,则创建新标签页打开翻译页面

功能总结

  1. 当用户选中网页文本
  2. 右键点击会显示"百度翻译:xxx"选项
  3. 点击后会在新标签页打开百度翻译,并自动填入选中的文本
  4. 支持自动检测语言并翻译成中文

这是一个实用的翻译工具扩展,可以快速翻译网页中选中的文本。

还没有评论,来说两句吧