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则改变了模式 页面布局如下:
  • 这样便是成功了

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

相关推荐
金金金__1 天前
Chrome插件开发:在网页上运行脚本
浏览器
金金金__1 天前
从0到1:手把手带你开发第一个Chrome插件
浏览器
敲代码的彭于晏5 天前
localStorage 不够用?试试 IndexedDB !
前端·javascript·浏览器
知心宝贝8 天前
写了那么久的前端,你真的了解浏览器背后的“小动作“吗?
前端·程序员·浏览器
mCell10 天前
JavaScript 运行机制详解:再谈 Event Loop
前端·javascript·浏览器
鹏多多11 天前
js使用History.replaceState实现不刷新修改浏览器url
前端·javascript·浏览器
辰九九13 天前
Uncaught URIError: URI malformed 报错如何解决?
前端·javascript·浏览器
PineappleCoder14 天前
浏览器垃圾回收机制:V8引擎的“清道夫”是怎样工作的?
前端·浏览器