Chrome插件开发:将脚本注入到当前活动的标签页中

金金金上线!

话不多,只讲你能听懂的前端知识

构建扩展程序

  • 创建一个名为 focus-mode 的新目录,用于存放扩展程序的文件

添加扩展程序数据和图标

  • 创建一个名为 manifest.json 的文件,并添加以下代码:

    json 复制代码
    {
      "manifest_version": 3,
      "name": "Focus Mode",
      "description": "Enable focus mode on Chrome's official Extensions and Chrome Web Store documentation.",
      "version": "1.0",
      "icons": {
        "16": "images/icon-16.png",
        "32": "images/icon-32.png",
        "48": "images/icon-48.png",
        "128": "images/icon-128.png"
      }
    }

提供图标

  • 创建一个 images 文件夹,并将图标放入其中(自行下载就好)

初始化扩展程序

  • 扩展程序可以使用扩展程序的服务工作器在后台监控浏览器事件。Service Worker 是一种特殊的 JavaScript 环境,用于处理事件,并在不需要时终止。
  1. 首先,在 manifest.json 文件中注册 Service Worker:

  2. 创建一个名为 background.js 的文件,并添加以下代码

启用扩展程序操作

  • 扩展程序操作用于控制扩展程序的工具栏图标。因此,每当用户点击扩展程序图标时,扩展程序都会运行一些代码(如本例所示)或显示弹出式窗口。添加以下代码以在 manifest.json 文件中声明扩展程序操作:

    json 复制代码
    "action": {
        "default_icon": {
          "16": "images/icon-16.png",
          "32": "images/icon-32.png",
          "48": "images/icon-48.png",
          "128": "images/icon-128.png"
        }
    }
  • 使用 "activeTab" 权限,在manifest.json加入如下代码:

    json 复制代码
    "permissions": ["activeTab"]

    activeTab 权限是浏览器扩展开发中最常用的权限之一,它的核心作用是 让扩展程序只在用户主动关注的标签页上运行代码

    🎯 主要作用

    1. 精准操作当前页面
      扩展只能在用户正在浏览的标签页上执行代码(如修改 DOM、注入脚本),不会影响其他标签页。
    2. 保护用户隐私
      由于扩展只能访问用户主动打开的标签页,避免了未经授权访问银行账户、私人聊天等敏感页面。
    3. 减少权限警告
      相比 tabs 权限(可访问所有标签页),activeTab 引发的权限提示更少,提升用户体验。

跟踪当前标签页的状态

  • 用户点击扩展程序操作后,该扩展程序会检查网址是否与文档页面匹配。接下来,它会检查当前标签页的状态并设置下一个状态。将以下代码添加到 background.js

    js 复制代码
    const extensions = 'https://developer.chrome.com/docs/extensions';
    const webstore = 'https://developer.chrome.com/docs/webstore';
    
    chrome.action.onClicked.addListener(async (tab) => {
      if (tab.url.startsWith(extensions) || tab.url.startsWith(webstore)) {
        // Retrieve the action badge to check if the extension is 'ON' or 'OFF'
        const prevState = await chrome.action.getBadgeText({ tabId: tab.id });
        // Next state will always be the opposite
        const nextState = prevState === 'ON' ? 'OFF' : 'ON';
    
        // Set the action badge to the next state
        await chrome.action.setBadgeText({
          tabId: tab.id,
          text: nextState,
        });
      }

添加或移除样式表

  • 现在,来更改页面的布局。创建一个名为 focus-mode.css 的文件,并添加以下代码:

    css 复制代码
    * {
      display: none !important;
    }
    
    html,
    body,
    *:has(article),
    article,
    article * {
      display: revert !important;
    }
    
    [role='navigation'] {
      display: none !important;
    }
    
    article {
      margin: auto;
      max-width: 700px;
    }
  • 使用 Scripting API 插入或移除样式表。首先,在清单中声明 "scripting" 权限:

    json 复制代码
    "permissions": ["activeTab", "scripting"],

background.js 中添加以下代码以更改页面的布局

js 复制代码
if (nextState === "ON") {
      // Insert the CSS file when the user turns the extension on
      await chrome.scripting.insertCSS({
        files: ["focus-mode.css"],
        target: { tabId: tab.id },
      });
    } else if (nextState === "OFF") {
      // Remove the CSS file when the user turns the extension off
      await chrome.scripting.removeCSS({
        files: ["focus-mode.css"],
        target: { tabId: tab.id },
      });
    }

分配键盘快捷键

  • 方便起见,添加了一个快捷方式,以便更轻松地启用或停用专注模式。将 "commands" 键添加到清单中

    json 复制代码
    "commands": {
        "_execute_action": {
          "suggested_key": {
            "default": "Ctrl+B",
            "mac": "Command+B"
          }
        }
      }

    "_execute_action" 按键会运行与 action.onClicked() 事件相同的代码,因此无需额外的代码。

测试是否生效

首先加载扩展程序,不会的看我这篇文章:juejin.cn/post/754171...

首先,打开以下任一页面:

然后,点击相应扩展程序操作。如果您设置了键盘快捷键,可以按 Ctrl + BCmd + B 对其进行测试。

  • 刚打开如下所示:
  • 按下ctrl+b则改变了模式 页面布局如下:
  • 这样便是成功了

编写有误还请各位指正,万分感谢

相关推荐
Wect5 天前
浏览器缓存机制
前端·面试·浏览器
FliPPeDround9 天前
浏览器扩展 E2E 测试的救星:vitest-environment-web-ext 让你告别繁琐配置
e2e·浏览器·测试
SuperEugene9 天前
浏览器存储:localStorage / sessionStorage / cookie 应该怎么用
前端·javascript·面试·浏览器
宁雨桥9 天前
浏览器渲染原理
前端·浏览器·原理
YZ09911 天前
2026年如何批量保存小红书作者主页的视频、图片和文案?
经验分享·浏览器·插件
程序员ys11 天前
网页白屏的原理与优化
前端·性能优化·浏览器
Wect13 天前
从输入URL到页面显示的完整技术流程
前端·面试·浏览器
NEXT0613 天前
从输入 URL 到页面展示的完整链路解析
网络协议·面试·浏览器
CappuccinoRose16 天前
CSS 语法学习文档(十五)
前端·学习·重构·渲染·浏览器
REDcker17 天前
Media Source Extensions (MSE) 详解
前端·网络·chrome·浏览器·web·js