Skip to content

常用 API 模式

按需注入 CSS

用户点击工具栏图标后,可借助 activeTabscripting 仅在当前页面临时注入样式。适合阅读模式、页面高亮等可切换功能。

js
chrome.action.onClicked.addListener(async (tab) => {
  if (!tab.id) return

  const current = await chrome.action.getBadgeText({ tabId: tab.id })
  const enabled = current !== 'ON'

  await chrome.action.setBadgeText({
    tabId: tab.id,
    text: enabled ? 'ON' : 'OFF',
  })

  if (enabled) {
    await chrome.scripting.insertCSS({
      target: { tabId: tab.id },
      files: ['focus-mode.css'],
    })
  } else {
    await chrome.scripting.removeCSS({
      target: { tabId: tab.id },
      files: ['focus-mode.css'],
    })
  }
})

徽标状态可按 tabId 保存,从而让不同标签页拥有独立状态。

标签页查询与分组

Popup 中可以查询匹配站点的标签页,按标题排序后渲染;在用户确认后使用 chrome.tabs.group()chrome.tabGroups.update() 创建分组。

js
const tabs = await chrome.tabs.query({
  url: ['https://developer.chrome.com/docs/*'],
})

const tabIds = tabs.flatMap((tab) => (tab.id === undefined ? [] : [tab.id]))
if (tabIds.length > 0) {
  const groupId = await chrome.tabs.group({ tabIds })
  await chrome.tabGroups.update(groupId, { title: 'Chrome Docs' })
}

该能力需要在 manifest 中声明 tabGroups;查询范围和可读取的标签信息受相应权限与 host permissions 约束。

地址栏关键词

使用 Omnibox 可以在地址栏中提供扩展专属关键词。用户输入 api 加空格后输入内容时,可展示建议并在确认后打开页面。

json
{
  "omnibox": {
    "keyword": "api"
  }
}
js
chrome.omnibox.onInputChanged.addListener(async (_input, suggest) => {
  const { history = [] } = await chrome.storage.local.get('history')
  suggest(history.map((item) => ({ content: item, description: item })))
})

chrome.omnibox.onInputEntered.addListener((input) => {
  chrome.tabs.create({ url: `https://developer.chrome.com/docs/extensions/reference/${input}` })
})

将搜索记录存入 chrome.storage.local,而不是依赖 service worker 内存。

定时刷新数据

chrome.alarms 用于安排未来或周期性任务。例如每天获取一次提示内容,并写入本地存储:

js
const alarmName = 'daily-tip'

chrome.runtime.onInstalled.addListener(async () => {
  await chrome.alarms.create(alarmName, { periodInMinutes: 24 * 60 })
})

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name !== alarmName) return

  const response = await fetch('https://example.com/tips.json')
  const tips = await response.json()
  await chrome.storage.local.set({ tip: tips[0] })
})

网络地址应通过 host_permissions 精确声明。定时任务可能因浏览器重启或扩展更新而被清除,启动时应检查并按需重新创建。

参考:chrome.actionChrome 扩展 API 参考

基于 MIT 许可发布