谷歌浏览器插件教程官方例子之注入打开的页面

Inject scripts into the active tab

单击扩展工具栏图标,简化当前页面的样式
主要是实现在指定的页面,匹配对应的页面,执行注入css和设置插件图标的Badge
效果如下:
黑白课堂
黑白课堂
黑白课堂
黑白课堂

配置 manifest.json

{
 "name": "Focus Mode",
  "description": "Enable focus mode on Chrome's official Extensions and Chrome Web Store documentation.","version":"1.0",
  //浏览器插件图标
  "action": {
    "default_icon": "img/logo.png"
  },
  //插件图标
  "icons": {
    "16": "img/logo.png",
    "32": "img/logo.png",
    "48": "img/logo.png",
    "128": "img/logo.png"
  },
  "content_scripts": [
    {
      "js": ["content.js"],
      "matches": [
        "https://developer.chrome.com/docs/extensions/*",
        "https://developer.chrome.com/docs/webstore/*"
      ]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["activeTab","scripting"],
  //快捷命令行
  "commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+B",
        "mac": "Command+B"
      }
    }
  }
}

background.js

//插件安装完成设置插件图标的Badge为OFF
chrome.runtime.onInstalled.addListener(() => {
    chrome.action.setBadgeText({
        text: "OFF",
    });
});
const extensions = 'https://developer.chrome.com/docs/extensions'
const webstore = 'https://developer.chrome.com/docs/webstore'

chrome.action.onClicked.addListener(async (tab) => {
    console.log('onClicked点击了',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'

        if (nextState === "ON") {
            // Insert the CSS file when the user turns the extension on
            await chrome.scripting.insertCSS({
                files: ["css/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: ["css/focus-mode.css"],
                target: { tabId: tab.id },
            });
        }

        // Set the action badge to the next state
        await chrome.action.setBadgeText({
            tabId: tab.id,
            text: nextState,
        });
    }
})

其中chrome.action.onClicked.addListener(async (tab) ....) 的 tab参数如下

{
active: true
audible: false
autoDiscardable: true
discarded: false
favIconUrl: "https://developer.chrome.com/images/meta/favicon-32x32.png"
groupId: -1
height: 937
highlighted: true
id: 193
incognito: false
index: 2
mutedInfo:
muted: false
[[Prototype]]: Object
pinned: false
selected: true
status: "complete"
title: "Chrome Extensions Tutorial: Focus Mode - Chrome Developers"
url: "https://developer.chrome.com/docs/extensions/mv3/getstarted/tut-focus-mode/"
width: 1920
windowId: 8
}

其中 id 通常就是我们说的tabId

focus-mode.css

body > .scaffold > :is(top-nav, navigation-rail, side-nav, footer),
main > :not(:last-child),
main > :last-child > navigation-tree,
main .toc-container {
    display: none;
}

main > :last-child {
    margin-top: min(10vmax, 10rem);
    margin-bottom: min(10vmax, 10rem);
}

评论区 (0)

没有记录
支持 markdown,图片截图粘贴拖拽都可以自动上传。
哪吒

哪吒 · 中级学士

热爱技术,喜欢新东西。

老程序员年度分享MVP
查看更多

最新视频课程